我并没有真正获得JavaScript原型。以此代码为例: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]”?!如果原始原型对象(新类(“proto_class”))正在被修改,那么asdf变量为什么不保留“changed_asdf”?如果不是,那为什么asdf2数组包含“changed_asdf2”?此外,如何确保每个新的SubClass()实例都包含一个新的Class()实例,就像在C++和Java中一样?