Reputation: 11184
Call the parent method.How to implement?
function Ch() {
this.year = function (n) {
return n
}
}
function Pant() {
this.name = 'Kelli';
this.year = function (n) {
return 5 + n
}
}
//extends
Pant.prototype = new Ch();
Pant.prototype.constructor = Pant;
pant = new Pant();
alert(pant.name); //Kelli
alert(pant.year(5)) //10
How to сall the parent method
this.year = function (n) {
return 5 + n
}
in object?Thank you all for your help
Upvotes: 1
Views: 130
Reputation: 71918
First of all, assuming Ch
is for "child", and Pant
for "parent", you are doing it backwards, which is extremely confusing. When you say
Pant.prototype = new Ch();
You're making Pant
inherit from Ch
. I'm assuming that's really what you mean, and that you want to call the method that returns n
, instead of the one that returns n + 5
. So you can do this:
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
Upvotes: 1
Reputation: 664650
Adapting this answer to your code:
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
Upvotes: 1
Reputation: 5443
Here is how Google's Closure Library implements inheritance:
goog.inherits = function(childCtor, parentCtor) {
function tempCtor() {};
tempCtor.prototype = parentCtor.prototype;
childCtor.superClass_ = parentCtor.prototype;
childCtor.prototype = new tempCtor();
childCtor.prototype.constructor = childCtor;
};
Your code would then become something like:
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
You could of course rename the goog.inherits
function if you wanted.
Upvotes: 1
Reputation: 23208
You can call overridden supper class(Parent) methods using __proto__
but it is not supported by IE
alert(pant.__proto__.year(5)) //5
Upvotes: 1