JavaScript';s匿名对象原型
我学习了JavaScript的“OOP”模型,并期待着得到一个建议,告诉我如何编写代码来解决我所面临的一些问题。(稍后我将使用术语“实例”,但现在我知道JavaScript中没有实例。)考虑下面的代码:JavaScript';s匿名对象原型,javascript,oop,scope,closures,prototype,Javascript,Oop,Scope,Closures,Prototype,我学习了JavaScript的“OOP”模型,并期待着得到一个建议,告诉我如何编写代码来解决我所面临的一些问题。(稍后我将使用术语“实例”,但现在我知道JavaScript中没有实例。)考虑下面的代码: function Class1(){ this.locvar1 = "locvar1"; this.locvar2 = "locvar2"; } function Class2(){ this.set = function(){ this.locv
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()之后仍然是一样的
当我试图在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:“}对象的原型,而不是“this.locvar1”的本地实例
我能肯定吗?我该如何编码呢?我试图更改“this.locvar1=new{a:“a”};”,因为这对我来说似乎是合乎逻辑的,但结果是一样的。
this.locvar1=new{a:“a”}
错误,请尝试this.locvar1={a:“ch_locvar1”}代码>这将为您提供您期望的原型继承:
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'
函数类1(){
this.locvar1={a:“a”};
this.locvar2=“locvar2”;
}
函数类2(){
这个.\uuuu proto\uuuu=new Class1()
this.set=函数(){
this.locvar1.a=“ch_locvar1”;
}
}
var x=新类2();
x、 set();
var y=新类2();
document.write(x.locvar1.a)//输出'ch_locvar1'
document.write(“
”)
document.write(y.locvar1.a)//输出'a'
当实例化Class2
时,我已经将prototype对象设置为newclass1
。它不能按您的方式工作,因为两个对象都将引用相同的原型对象,而JavaScript是按引用传递的,正如其他人所解释的。在JavaScript中,对象是按引用传递的。这就是为什么在第二个示例中,locvar1
发生了变化。我不确定您预期会发生什么…?似乎CoffeeScript按照您预期的方式进行编译:我不确定这是如何回答问题的。应该避免使用\uu proto\uu
,并且不适用于所有浏览器。@Sarfraz真的吗?我不知道。那么,怎样才能跨浏览器完成我的代码片段呢?谢谢。要么是\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
要么是原型
。
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'