调用父方法。如何实现?
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
}
对象?谢谢大家的帮助
答案 0 :(得分:1)
您可以使用__proto__
调用重写的超类(父)方法,但IE不支持
alert(pant.__proto__.year(5)) //5
答案 1 :(得分:1)
以下是Google's Closure Library实现继承的方式:
goog.inherits = function(childCtor, parentCtor) {
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
};
您的代码将变为类似:
function Ch() {}
Ch.prototype.year =
function (n) {
return n
}
function Pant() {}
goog.inherits(Pant,Ch);
Pant.prototype.name = 'Kelli';
Pant.prototype.year = function (n) {
return 5 + Pant.superClass_.year.call(this, n);//Call the parent class
}
pant = new Pant();
alert(pant.name); //Kelli
alert(pant.year(5)) //10
如果需要,您当然可以重命名goog.inherits
功能。
答案 2 :(得分:1)
使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
答案 3 :(得分:1)
首先,假设Ch
用于" child"和Pant
用于" parent",您正在向后执行,这非常令人困惑。当你说
Pant.prototype = new Ch();
您正在Pant
继承Ch
。我假设你的意思是真的,并且你想要调用返回n
的方法而不是返回n + 5
的方法。所以你可以这样做:
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
// Is the below what you need?
alert(Pant.prototype.year(5)); // 5