【发布时间】:2010-08-26 03:57:34
【问题描述】:
我并没有真正了解 JavaScript 原型。以这段代码为例:
function Class(asdf) {
if(typeof(asdf) == 'undefined') {
} else {
this.asdf = asdf;
}
}
Class.prototype.asdf = "default_asdf";
Class.prototype.asdf2 = [];
Class.prototype.change_asdf = function() {
this.asdf = "changed_asdf";
this.asdf2.push("changed_asdf2");
}
function SubClass() {
}
SubClass.prototype = new Class("proto_class");
SubClass.prototype.constructor = SubClass;
test1 = new SubClass();
alert("test1 asdf: " + test1.asdf + " " + test1.asdf2);
test1.change_asdf();
alert("test1 asdf: " + test1.asdf + " " + test1.asdf2);
test2 = new SubClass();
alert("test2 asdf: " + test2.asdf + " " + test2.asdf2);
第一个警报按预期打印“proto_class []”。第二个警报也按预期打印“changed_asdf [changed_asdf2]”。但是为什么第三个警报会打印“proto_class [changed_asdf2]”?!如果原始原型对象 (new Class("proto_class")) 正在修改,那么为什么 asdf 变量不保持“changed_asdf”?如果不是,那么为什么 asdf2 数组包含“changed_asdf2”?此外,我如何确保每个新的 SubClass() 实例都包含一个新的 Class() 实例,就像在 C++ 和 Java 中一样?
【问题讨论】:
标签: javascript oop subclass