构造函数函数闭包变量

constructor function closure variable

本文关键字:变量 闭包 函数 构造函数      更新时间:2023-09-26

对于下面的函数,我希望a和b有自己的数组版本,因此希望输出为false,但输出为true。谁能解释一下,为什么?

 function Test() { 
    var a = [1,2,3]; 
    Test.prototype.getArray = function() { return a; };
 }
var a = new Test();
var b = new Test();
console.log(a.getArray() === b.getArray());

每个Test对象都继承相同的原型。完全相同的原型。由于您正在覆盖原型函数,因此它将覆盖该类型的所有对象。

示例:

function log(msg) {
  document.querySelector('pre').innerText += msg + ''n';
}
function Person(name) {
  this.name = name;
}
Person.prototype.sayHello = function() {
  log('Hello, ' + this.name);
};
var bob = new Person('Bob');
var alice = new Person('Alice');
bob.sayHello();
alice.sayHello();
// Overwriting the prototype function
Person.prototype.sayHello = function() {
  log('Goodbye, ' + this.name);
};
bob.sayHello();
alice.sayHello();
<pre></pre>

如果您绝对需要使用标准构造函数访问函数中的私有数据,则需要在构造函数本身中定义函数。

function Test() {
  var a = [1,2,3];
  this.getArray = function() {
    return a;
  };
}

请注意,在许多实现中,这会否定您从原型继承中获得的大量空间和性能优化。