简体   繁体   English

ES5构造函数中定义的私有变量之谜

[英]ES5 puzzle of private variable defined in constructor

I am reading the Private Variable section in "Professional JavaScript for Web Developers 3rd Edition", and feel puzzled about one of the sample codes: 我正在阅读“面向Web开发人员的专业JavaScript第三版”中的“ 私有变量”部分,并对示例代码之一感到困惑:

function Person(name) {
  this.setName = function(value) {
    name = value;
  }

  this.getName = function() {
    return name;
  }
}

var person1 = new Person('p1');
person1.setName('p11');
person1.getName();  // 'p11'

var person2 = new Person('p2');
person2.getName();  // 'p2'

The getName() method accesses the name variable via the closure and scope chain, while the setName() method assigns a new value to name . getName()方法通过闭包和作用域链访问name变量,而setName()方法为name分配一个新值。

Question: 题:

Where does the name variable exist? name变量在哪里存在?

Why does every instance of Person have a different name , so that if one instance modifies the name variable it would not affect other instances? 为什么Person每个实例都具有不同的name ,因此,如果一个实例修改了name变量,则不会影响其他实例?

==================================== ====================================

I think that every time an instance is created with new , there a Person Activation Object is being created. 我认为每次使用new创建实例时,都会创建一个Person Activation Object The name variable in the every Person Activation Object is different. 每个Person Activation Objectname变量都不相同。

This behaviour has nothing to do with new . 此行为与new无关。

Every time you invoke Person , a new, separate instance of the parameter variable name is created. 每次调用Person ,都会创建一个新的,单独的参数变量name实例。 The code inside that function can access that variable. 该函数内部的代码可以访问该变量。 There is nothing more to it. 没什么了。

This is true for parameter variables in every function you may declare. 对于您可以声明的每个函数中的参数变量,都是如此。 As long as it is possible to reference such variables they remain in memory -- they are not garbage collected. 只要可以引用这些变量,它们就保留在内存中-不会被垃圾回收。

Calling Person twice, is in essence not much different then calling 2 different functions which both have the same parameters and methods: 两次调用Person ,本质上与调用两个具有相同参数和方法的不同函数没有太大区别:

function Person1(name) {
  this.setName = function(value) {
    name = value;
  }

  this.getName = function() {
    return name;
  }
}

function Person2(name) {
  this.setName = function(value) {
    name = value;
  }

  this.getName = function() {
    return name;
  }
}

var person1 = new Person1('p1');
person1.setName('p11');
person1.getName();  // 'p11'

var person2 = new Person2('p2');
person2.getName();  // 'p2'

Of course, here person1 and person2 are no longer the instance of the same constructor, but besides that the principle of separate variable instances and scopes is the same. 当然,这里的person1person2不再是同一构造函数的实例,但除此之外,单独的变量实例和作用域的原理是相同的。

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

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