Ok, we can have private identifiers in javascript, but what about protected ones?

a 夏天 提交于 2019-12-21 20:13:32

问题


Simple as that, can we emulate the "protected" visibility in Javascript somehow?


回答1:


Do this:

/* Note: Do not break/touch this object */
...code...

Or a bit of google found this on the first page:

http://blog.blanquera.com/2009/03/javascript-protected-methods-and.html




回答2:


Sure you can. Here's another example.




回答3:


What could that possibly mean? You don't have classes.

I suppose you could analyze caller to determine whether it meets some set of criteria for being permitted to call a method. This will be hideously inefficient and your criteria will always be spoofable.




回答4:


There's an interesting pattern worth mentioning here: a JavaScript contructor function may return any object (not necesserily this). One could create a constructor function, that returns a proxy object, that contains proxy methods to the "real" methods of the "real" instance object. This may sound complicated, but it is not; here is a code snippet:

var MyClass = function() {
    var instanceObj = this;
    var proxyObj = {
        myPublicMethod: function() {
            return instanceObj.myPublicMethod.apply(instanceObj, arguments);
        }
    }
    return proxyObj;
};
MyClass.prototype = {
    _myPrivateMethod: function() {
        ...
    },
    myPublicMethod: function() {
        ...
    }
};

The nice thing is that the proxy creation can be automated, if we define a convention for naming the protected methods. I created a little library that does exactly this: http://idya.github.com/oolib/



来源:https://stackoverflow.com/questions/1015017/ok-we-can-have-private-identifiers-in-javascript-but-what-about-protected-ones

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!