【发布时间】:2017-09-04 19:21:31
【问题描述】:
我有以下代码。为什么三个对象都引用同一个数组,而字符串变量是独立的?如何在不显式添加的情况下修复它:function B(){this.arr = [];}
function A(){
this.text = "";
this.arr = [];
this.action = function(){
this.text+="z";
this.arr.push(1);
}
this.test = function(){
console.log(this.text+"|"+this.arr);
}
}
function B(){
}
B.prototype = new A();
B.prototype.constructor = B;
var B1 = new B();
var B2 = new B();
var B3 = new B();
B1.action();
B2.action();
B3.action();
B1.test(); //z|1,1,1
B2.test(); //z|1,1,1
B3.test(); //z|1,1,1
【问题讨论】:
-
你应该使用
function B() { A.call(this) }而不是重复父构造函数所做的一切。
标签: javascript oop prototypal-inheritance