我学习了 JavaScript 的“OOP”模型,并期待获得有关如何围绕我遇到的一些问题进行编码的建议。 (稍后我将使用术语“实例”,但现在我知道 JavaScript 中没有实例。)考虑以下代码:
function Class1(){
this.locvar1 = "locvar1";
this.locvar2 = "locvar2";
}
function Class2(){
this.set = function(){
this.locvar1 = "ch_locvar1";
}
}
Class2.prototype = new Class1;
//we'll get two instances from Class2
var x = new Class2();
x.set(); // we'll change the x's field with that (hoping that)
var y = new Class2(); // hoping that this will be a totally new instance,
// and the previous set() won't change it at all
好的,代码将按我想要的方式工作。我创建了两个新对象,以及它们的原型(prototype) 在我调用 x.set() 之后仍然是一样的。
x.locvar1's value: "ch_locvar1"
x.locvar2's value: "locvar2"
y.locvar1's value: "locvar1"
y.locvar2's value: "locvar2"
their prototypes value:
locvar1 : "locvar1",
locvar2 : "locvar2"
当我尝试在 Class1 的字段中使用更多对象时,问题就来了。
function Class1(){
this.locvar1 = {a : "a"};
this.locvar2 = "locvar2";
}
function Class2(){
this.set = function(){
this.locvar1.a = "ch_locvar1";
}
}
Class2.prototype = new Class1;
var x = new Class2();
x.set();
var y = new Class2();
那会出来:
x.locvar1.a's value: "ch_locvar1"
x.locvar2's value: "locvar2"
what's ok, but..:
y.locvar1.a's value: "ch_locvar1"
y.locvar2's value: "locvar2"
their prototypes value:
locvar1.a : "ch_locvar1",
locvar2 : "locvar2"
所以看起来像声明“this.locvar1.a”我全局更改了{a:“a”}对象的原型(prototype),而不是“this.locvar1”的本地实例......
我确定吗?我该如何编码?我试图改变“this.locvar1 = new {a:“a”};”因为这对我来说似乎合乎逻辑,但结果是一样的。
最佳答案
这将为您提供您期望的原型(prototype)继承:
function Class1(){
this.locvar1 = {a : "a"};
this.locvar2 = "locvar2";
}
function Class2(){
this.__proto__ = new Class1()
this.set = function(){
this.locvar1.a = "ch_locvar1";
}
}
var x = new Class2();
x.set();
var y = new Class2();
document.write(x.locvar1.a) // outputs 'ch_locvar1'
document.write('<br />')
document.write(y.locvar1.a) // outputs 'a'
当 Class2
实例化时,我已将原型(prototype)对象设置为 new Class1
。它不会以您的方式工作,因为两个对象将引用相同的原型(prototype)对象,而 JavaScript 是通过引用传递的,正如其他人所解释的那样。
关于JavaScript 的匿名对象原型(prototype),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9239661/