我学习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
好的,代码将以我想要的方式工作。我创建了两个新对象及其原型 在我调用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”}对象的原型,而不是“this.locvar1”的本地实例......
我确定吗?我怎么能围绕它编码?我试图改变“this.locvar1 = new {a:”a“};”因为这对我来说似乎合乎逻辑,但结果是一样的。
答案 0 :(得分:1)
this.locvar1 = new {a : "a"};
错误,请尝试this.locvar1 = {a : "ch_locvar1"};
。
答案 1 :(得分:1)
这将为您提供您期望的原型继承:
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'
在实例化new Class1
时,我已将原型对象设置为Class2
。它不起作用,因为两个对象将引用相同的原型对象,JavaScript通过引用传递,正如其他人所解释的那样。