调用父方法。如何实现?
function Ch() {
this.year = function (n) {
return n
}
}
function Pant() {
this.name = 'Kelli';
this.year = function (n) {
return 5 + n
}
}
//扩展
Pant.prototype = new Ch();
Pant.prototype.constructor = Pant;
pant = new Pant();
alert(pant.name); //Kelli
alert(pant.year(5)) //10
如何使用所有父方法
this.year = function (n) {
return 5 + n
}
反对?谢谢大家的帮助
最佳答案
使this answer适应您的代码:
function Ch() {
this.year = function(n) {
return n;
}
}
function Pant() {
Ch.call(this); // make this Pant also a Ch instance
this.name = 'Kelli';
var oldyear = this.year;
this.year = function (n) {
return 5 + oldyear(n);
};
}
// Let Pant inherit from Ch
Pant.prototype = Object.create(Ch.prototype, {constructor:{value:Pant}});
var pant = new Pant();
alert(pant.name); // Kelli
alert(pant.year(5)) // 10