好吧,我有一个带有一个秘密和一个方法的构造函数:
function Keeper(get) {
var secretPower = 'wisdom';
this.get = get ? get : function () {
return 'Its secret power is: ' + secretPower;
}
// now this is privileged method only in case that there are no arguments?
}
现在我将创建两个实例,一个具有特权方法...
var yourKeeper = new Keeper();
yourKeeper.get(); // "Its secret power is: wisdom"
...但另一个是不同的。它可以触及它周围的上下文,但不能触及构造函数的私有...
var myKeeper = new Keeper(function() {
return 'Its secret power is: ' + secretPower;
});
myKeeper.get(); // ReferenceError: secretPower is not defined
...这也不能按我的意愿工作:
myKeeper.get = function() {
return 'Its secret power is: ' + secretPower;
}
myKeeper.get(); // ReferenceError: secretPower is not defined
当然它不会起作用,因为secretPower
在这些情况下是全局变量,所以:
var secretPower = 'none';
myKeeper.get(); // "Its secret power is: none"
那么是否可以在构造函数之外定义特权方法?如何?
可以用eval完成吗?(我知道......这是邪恶的......我只是感兴趣)