【发布时间】:2012-02-11 10:59:10
【问题描述】:
我学习 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"};”因为这在我看来是合乎逻辑的,但结果是一样的。
【问题讨论】:
-
在 javascript 中对象是通过引用传递的。这就是为什么在第二个示例中
locvar1发生了变化。 -
我不确定你期望发生什么...?
-
CoffeeScript 似乎按照您的预期编译它:jsfiddle.net/nfJDk/14
标签: javascript oop scope closures prototype