Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

javascript - 从原型定义的函数访问私有成员变量(Accessing private member variables from prototype-defined functions)

Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?(有没有办法制作“私有”变量(在构造函数中定义的变量),可用于原型定义的方法?)

TestClass = function(){
    var privateField = "hello";
    this.nonProtoHello = function(){alert(privateField)};
};
TestClass.prototype.prototypeHello = function(){alert(privateField)};

This works:(这有效:)

t.nonProtoHello()

But this doesn't:(但这不是:)

t.prototypeHello()

I'm used to defining my methods inside the constructor, but am moving away from that for a couple reasons.(我习惯在构造函数中定义我的方法,但由于一些原因,我正在远离它。)

  ask by morgancodes translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()); };

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...