[英]What is wrong with my approach to Javascript Inheritance?
我知道有很多方法可以進行JS繼承。 我試圖在這里做一些事情,在這里我將行傳遞到我的子類中,我想在構造函數時將其傳遞給超類:
function AbstractTableModel(rows) {
this.showRows = function() {
alert('rows ' + this.rows);
}
}
function SolutionTableModel(rows) {
this.prototype = new AbstractTableModel(rows);
this.show = function() {
this.protoype.showRows();
};
}
var stm = new SolutionTableModel(3);
stm.show();
小提琴:
它似乎不起作用,因為原型方法沒有順暢:(有什么想法嗎?
首先,您必須定義this.rows
function AbstractTableModel(rows) {
this.rows = rows;
this.showRows = function() {
alert('rows ' + this.rows);
};
}
其次,如果要從AbstractTableModel
繼承,則應該這樣做。
function SolutionTableModel(rows) {
AbstractTableModel.call(this, rows);
this.show = function() {
this.showRows();
};
}
SolutionTableModel.prototype = new AbstractTableModel();
var stm = new SolutionTableModel(3);
stm.show();
/ ================================================= =========================== /
如果要避免兩次調用基本構造函數,也可以使用“寄生組合繼承模式”:
function inheritPrototype(subType, superType) {
var prototype = Object.create(superType.prototype, {
constructor: {
value: subType,
enumerable: true
}
});
subType.prototype = prototype;
}
function AbstractTableModel(rows) {
this.rows = rows;
this.showRows = function () {
alert('rows ' + this.rows);
};
}
function SolutionTableModel(rows) {
AbstractTableModel.call(this, rows);
this.show = function () {
this.showRows();
};
}
inheritPrototype(AbstractTableModel, SolutionTableModel);
var stm = new SolutionTableModel(3);
stm.show();
function AbstractTableModel(rows) {
this.rows = rows;
this.showRows = function() {
alert('rows ' + this.rows);
}
}
function SolutionTableModel(rows) {
var soln = Object.create(new AbstractTableModel(rows));
soln.show = function() {
this.showRows();
};
return soln;
}
var solution = new SolutionTableModel(5);
solution.show();
function AbstractTableModel(rows) {
this.rows = rows;
}
AbstractTableModel.prototype.showRows = function() {
console.log('rows ' + this.rows);
}
function SolutionTableModel(rows) {
AbstractTableModel.call(this, rows);
this.show = function() {
this.showRows();
};
}
SolutionTableModel.prototype = Object.create(AbstractTableModel.prototype);
var stm = new SolutionTableModel(3);
stm.show();
這是一個基於您所做的DEMO的工作示例:
function AbstractTableModel(rows) {
this.showRows = function () {
alert('rows ' + rows);
}
}
function SolutionTableModel(rows) {
var self = this;
this.prototype = new AbstractTableModel(rows);
this.show = function () {
self.prototype.showRows();
};
}
var stm = new SolutionTableModel(3);
stm.show();
AbstractTableModel
,沒有this.rows
直接使用rows
。 SolutionTableModel
。 我更喜歡定義變量self
來指向對象的創建實例。 protoype
應該是prototype
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.