简体   繁体   English

可以使用公共方法访问私有类的属性吗?

[英]Can one access a private class property in a public method?

Newbie Javascript question: 新手Javascript问题:

how does one access a private class property in a public method? 如何使用公共方法访问私有类的属性? In all the example I see a public prototype function accessing public (this.property). 在所有示例中,我看到一个公共原型函数正在访问public(this.property)。 Is it possible to access a private property in a public method? 是否可以通过公共方法访问私有财产?

This pattern is known as a "privileged" method. 这种模式称为“特权”方法。 It looks something like this: 看起来像这样:

function MyClass() {
  var secret = "foo";
  this.tellSecret = function() {
    return secret;
  };
}

var inst = new MyClass();
console.log(inst.tellSecret()); // => "foo"
console.log(inst.secret);       // => undefined

This works because the private variable is in a closure. 这是可行的,因为私有变量在闭包中。 The problem with this is that we are putting the privileged method on each instance, rather than the prototype. 问题在于,我们将特权方法放在每个实例上,而不是原型上。 This is not ideal. 这是不理想的。 Often, instead of having private variables in JavaScript, authors will just use a leading underscore which is conventionally used to imply that public methods/properties should be treated as private: 通常,作者不会在JavaScript中使用私有变量,而只会使用前导下划线,该下划线通常用来暗示将公共方法/属性视为私有:

function MyClass() {
  this._secret = "foo";
}

MyClass.prototype.tellSecret = function() {
  return this._secret;
};

Here is a little demo: 这是一个小演示:

var Foo = function(name){ 
    this.name = name; 
    var t = name; 
    if(typeof(this.show) != 'function'){
        Foo.prototype.show = function(){
            console.log(t);
            console.log(this.name);
        };
    }
};

var a = new Foo('a');
var b = new Foo('b');
b.show(); // ...

Hope it can help you out. 希望它可以帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM