[英]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.