Green
Green

Reputation: 30795

How to call a parent method from within a child method?

I have such a code:

function A() {
    this.hello = function() {
        console.log("I'm A");
    }
}

function B() {
    this.hello = function() {

        // I need to call A.hello here, like parent.hello();
        B.prototype.hello();   // This is wrong, TypeError

        console.log("I'm B");
    }
}

B.prototype = new A();
var b = new B();

b.hello();
#=> TypeError: Cannot call method 'hello' of undefined

I read some similar questions here but they all use this technique, they assign a method to a prototype.

FaqPage.prototype.init = function(name, faq) {
    BasePage.prototype.init.call(this, name);
    this.faq = faq; 
}
FaqPage.prototype.getFaq = function() {
    return this.faq;
}

But it is not in my case. My prototype is a parent's instance. How may call a parent method in my case? Or do I have to refactor my code?

Upvotes: 3

Views: 72

Answers (1)

Nunners
Nunners

Reputation: 3047

You need to assign the this.hello a value, at the moment you are just creating a function to run.

Try the following :

function A() {
    this.hello = function() {
        console.log("I'm A");
    }
}

function B() {
    this.hello = function() {    
        B.prototype.hello();   // Now runs correctly and logs "I'm A"

        console.log("I'm B");
    }
}

B.prototype = new A();
var b = new B();

b.hello();

By changing the code to be this.hello = function() { } we are creating a property of the object that can be called from outside the object.

The result of calling b.hello(); is :

I'm A
I'm B

Example JSFiddle

Upvotes: 3

Related Questions