构造函数内的公共与私有属性

Jos*_*ose 4 javascript variables constructor object

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

关于构造函数,我试图确定变量和函数默认是公共的还是私有的.

例如,我有这个样本构造函数具有以下属性:

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

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

var box = new Obj();
box.type; // 'object'
box.print(); // 'hello world'
Run Code Online (Sandbox Code Playgroud)

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

谢谢.

jfr*_*d00 6

Javascript中的实例上的所有属性(您分配的内容this.property = xxx)都是公共的 - 无论它们是在构造函数中还是在其他位置分配.

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

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

所以,在你的例子中:

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

所有属性type,questions并且print可公开访问.


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

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);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是使用构造函数闭包创建私有访问的更常见参考之一:http://javascript.crockford.com/private.html.