Simple as that, can we emulate the "protected" visibility in Javascript somehow?
4 回答
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
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.
这里有一个有趣的模式值得一提:JavaScript 构造函数可以返回任何对象(不一定是this)。可以创建一个构造函数,它返回一个代理对象,其中包含对“真实”实例对象的“真实”方法的代理方法。这听起来可能很复杂,但事实并非如此;这是一个代码片段:
var MyClass = function() {
var instanceObj = this;
var proxyObj = {
myPublicMethod: function() {
return instanceObj.myPublicMethod.apply(instanceObj, arguments);
}
}
return proxyObj;
};
MyClass.prototype = {
_myPrivateMethod: function() {
...
},
myPublicMethod: function() {
...
}
};
好处是代理创建可以自动化,如果我们定义一个命名受保护方法的约定。我创建了一个这样做的小库:http: //idya.github.com/oolib/