Ok, we can have private identifiers in javascript,

2019-04-11 10:45发布

问题:

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/