Это потому, что вы пишете
SubClass.prototype = new Class("proto_class");
, вы создаете прототип один экземпляр из Class
.Вам нужно создать подкласс, который наследуется от прототипа его родителя.Как показывает Дэвид Фланаган в своем JavaScript: Полное руководство (§ 9.5), вы должны использовать вспомогательную функцию для создания нового объекта с указанным прототипом:
function heir(p) {
function f(){} // dummy constructor function
f.prototype = p; // specify prototype object we want
return new f(); // create and return new object
}
(Крокфордвызывает эту функцию Object.create
после так называемого свойства конструктора объекта ES5 , но, пожалуйста, не делайте этого, поскольку может вводить в заблуждение .)
В конструкторе SubClass вам необходимо вызвать конструктор класса с this
, установленным на текущий объект:
function SubClass() {
// call the parent's constructor with
// `this` set to the current scope
Class.call(this, "proto_class");
}
И, наконец, вы только сбросите Class.asdf2
один раз, но не в функции конструктора Class
или SubClass
.Поэтому добавьте this.asdf2 = [];
к одному из конструкторов.
Полный код теперь выглядит так:
function heir(p) {
function f(){} // dummy constructor function
f.prototype = p; // specify prototype object we want
return new f(); // create and return new object
}
function Class(asdf) {
if (typeof asdf != 'undefined')
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() {
// call the parent's constructor with
// `this` set to the current scope
Class.call(this, "proto_class");
this.asdf2 = [];
}
SubClass.prototype = heir(Class.prototype);
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);