JavaScript 繼承


//父類
function ClassA(sColor) {
//Define Properties
this.color = sColor;
this.drivers = new Array("Mike","John");

this.showColor = function() {
prt(this.color);
};
}

//父類
function ClassB(sName) {
this.name = sName;

this.sayName = function () {
prt(this.name);
};
}

//子類,多重繼承父類 ClassA, ClassB
function ClassC(sColor, sName, sType) {
ClassA.call(this, sColor);
ClassB.call(this, sName);

this.type = sType;

this.sayType = function () {
prt(this.type);
};
}

obj = new ClassC("BLUE", "Saab", "Advanced");

obj.showColor();
obj.sayName();
obj.sayType();

Question:構造函數會爲每個對象都創建獨立的函數版本。事實上,每個對象應該共享同一個函數。

[b]改進版:原型鏈方法[/b]
function ClassA(sColor) {
this.color = sColor;

if (ClassA._initialized) return;
ClassA._initialized = true;

ClassA.prototype.sayColor = function() {
prt(this.color);
};
}

function ClassB(sColor, sName) {
ClassA.call(this, sColor);
this.name = sName;

if (ClassB._initialized) return;
ClassB._initialized = true;

prt("Init");
ClassB.prototype.sayName = function() {
prt(this.name);
};
}
ClassB.prototype = new ClassA();

var b = new ClassB("RED", "BMW");
b.sayColor(); //inherit from parent method
b.sayName();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章