javascript中的私有成员真的那么复杂吗?

时间:2018-02-06 00:50:46

标签: javascript private-members

我试图通过Javascript澄清我对私人成员的理解。看起来应该很容易:

function MyClass(param) {
  var thisIsPrivate = param;
  this.getPrivateMember = function() {
    return thisIsPrivate;
  }
}

var thing = new MyClass('tada!');

console.log(thing.thisIsPrivate)       // undefined
console.log(thing.getPrivateMember())  // "tada!"

在我的阅读中,我不断发表文章,甚至不提这个选项,而是提出复杂的解决方案,比如使用闭包或WeakMaps。通常结论是,在Javascript中没有与私人成员合作的好方法。

任何人都可以填写我失踪的内容吗?出于某种原因,这是一个坏主意吗?

1 个答案:

答案 0 :(得分:0)

感谢您的回复。所以我对这种方法的局限性的理解是,在构造函数之外添加的方法无法看到“私有”变量。我觉得有些开悟。

function MyClass(param) {
  var thisIsPrivate = param;
  this.getPrivateMember = function() {
    return thisIsPrivate;
  }
}

MyClass.prototype.showPrivateMember = function(){
  console.log(thisIsPrivate);
}

var thing = new MyClass('tada!');

console.log(thing.thisIsPrivate)       // undefined
console.log(thing.getPrivateMember())  // tada!

thing.showPrivateMember(); // ReferenceError: thisIsPrivate is not defined at MyClass.showPrivateMember

thing.showPrivateMember = function(){
  console.log(thisIsPrivate);
}

thing.showPrivateMember(); // ReferenceError: thisIsPrivate is not defined at MyClass.showPrivateMember
相关问题