我並沒有真正獲得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中一樣?