【发布时间】:2016-02-03 12:45:15
【问题描述】:
这可能是老问题,但我仍然无法理解其背后的理论。
我们有
function Test(name) {
this.name = name;
}
Test.prototype.myArray = []; // I know if i move this to constructor it can resolve my problem
Test.prototype.what = function() {
document.writeln("<br/>" + this.myArray);
}
Test.prototype.add = function() {
this.myArray.push(this.name);
}
var a = new Test('Scott');
a.add();
a.what();
var b = new Test('Smith');
document.writeln("<br/>" + b.myArray + " <= Check this one")
b.add()
b.what();
没有人接触 b 对象数组,为什么 javascript 引擎从类原型中获取它,为什么不只取属于该对象的空数组。
编辑:
所有答案都是正确的,让我们将属性类型更改为原始类型
function Test(name) {
this.name = name;
}
Test.prototype.primitive = 1;
Test.prototype.myArray = []; // I know if i move this to constructor it can resolve my problem
Test.prototype.what = function() {
document.writeln("<br/>" + this.myArray + " primitive:" +this.primitive);
}
Test.prototype.add = function() {
this.primitive++;
this.myArray.push(this.name);
}
var a = new Test('Scott');
a.add();
a.what();
var b = new Test('Smith');
document.writeln("<br/>" + b.myArray + " primitive:" +b.primitive +" <= Check this one now primtive is not shared")
b.add()
b.what();
所以结论是所有附加到顶级原型的引用类型都共享给所有实例,像数字这样的原始数据类型不是。
【问题讨论】:
-
这就是 javascript 中属性查找的工作方式。当您编写
a.myArray时,引擎首先检查a是否有一个名为myArray的属性。由于它不引擎上升原型链。因此,每当您访问myArray(使用任何共享相同原型的起始对象)时,您将获得相同的数组,除非您在对象本身上定义myArray属性。
标签: javascript oop inheritance