Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 660
Green Avatar asked Jan 19 '26 13:01

Green


1 Answers

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

like image 154
Nunners Avatar answered Jan 21 '26 04:01

Nunners



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!