建筑商内部的公共与私人财产

Public vs Private Properties Inside Constructors

本文关键字:财产 内部 建筑商      更新时间:2023-09-26

我发现了类似的问题,但没有明确回答,所以我希望有人能帮我解决这个问题。

关于构造函数,我试图弄清楚变量和函数在默认情况下是公共的还是私有的

例如,我有一个具有以下属性的示例构造函数:

function Obj() {
  this.type = 'object';
  this.questions = 27;
  this.print = function() {
    console.log('hello world');
  }
}

我可以这样称呼这些属性:

var box = new Obj();
box.type; // 'object'
box.print(); // 'hello world'

在我看来,函数和变量在默认情况下都是公共的。是这样吗?或者,如果构造函数内部的函数是私有的。。。他们只能将私有变量作为参数吗

谢谢。

Javascript中实例上的所有属性(用this.property = xxx分配的东西)都是公共的,无论它们是在构造函数中还是在其他地方分配的。

如果使用Object.defineProperty(),给定的属性可能是只读的,也可能是getter或setter,但它们对外部世界都是可见的。

Javascript没有用于"私有"属性的内置语言功能。您可以将构造函数中的局部变量或局部函数用作私有函数,但它们仅可用于构造函数中定义的代码或方法。

因此,在您的示例中:

function Obj() {
  this.type = 'object';
  this.questions = 27;
  this.print = function() {
    console.log('hello world');
  }
}

所有属性typequestionsprint都是可公开访问的。


创建"私有"方法的一种技术是在构造函数中定义一个本地函数,如下所示:

function Obj() {
  var self = this;
  // this is private - can only be called from within code defined in the constructor
  function doSomethingPrivate(x) {
      console.log(self.type);
  }
  this.type = 'object';
  this.questions = 27;
  this.print = function(x) {
    doSomethingPrivate(x);
  }
}

以下是关于使用构造函数闭包创建私有访问的一个更常见的引用:http://javascript.crockford.com/private.html.