No, there's no way to do it.(不,没有办法做到这一点。)
That would essentially be scoping in reverse.(这基本上是反过来的范围。)
Methods defined inside the constructor have access to private variables because all functions have access to the scope in which they were defined.(构造函数中定义的方法可以访问私有变量,因为所有函数都可以访问定义它们的作用域。)
Methods defined on a prototype are not defined within the scope of the constructor, and will not have access to the constructor's local variables.(原型上定义的方法未在构造函数的范围内定义,并且无法访问构造函数的局部变量。)
You can still have private variables, but if you want methods defined on the prototype to have access to them, you should define getters and setters on the this
object, which the prototype methods (along with everything else) will have access to.(您仍然可以拥有私有变量,但是如果您希望在原型上定义的方法可以访问它们,则应该在this
对象上定义getter和setter,原型方法(以及其他所有内容) 将具有访问权限。)
For example:(例如:)
function Person(name, secret) {
// public
this.name = name;
// private
var secret = secret;
// public methods have access to private members
this.setSecret = function(s) {
secret = s;
}
this.getSecret = function() {
return secret;
}
}
// Must use getters/setters
Person.prototype.spillSecret = function() { alert(this.getSecret()); };
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…