Varun Sridharan
Varun Sridharan

Reputation: 1978

Call Childs Function From Parents Class in Javascript

Hi I have 2 JS Class like below

class WPOnion_Field_API2 {
    constructor() {
        wp.hooks.addAction( 'wponion_reload_fields', this.init_fields );
    }

    js_settings(elem, _default) {
        return wponion.field_js_args( elem, _default );
    }

    is_valid() {
        return ( 1 >= this.elem );
    }

    init_fields() {
        console.log( 11111 );
    }
}

Extended Class

class WPOnion_Field_inputmas extends WPOnion_Field_API2 {
    constructor() {
        super();
    }

    init_fileds() {
        console.log( 1 );
    }
}

let WPOFInputMask = new WPOnion_Field_inputmas();

In the first class u can see i used the called this.init_fields which means the class its extended with should call the childs function but its calling its own class's function.

Upvotes: 0

Views: 36

Answers (2)

Ritwick Dey
Ritwick Dey

Reputation: 19012

I think you're asking how to call parent class's method from child class.

If yes, use super.parentClassMethodName() from child class if child class has also same name.

Ref : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super

Upvotes: 0

Scott Marcus
Scott Marcus

Reputation: 65796

You didn't call this.init_fields in the constructor of the base class. You only referenced it:

wp.hooks.addAction( 'wponion_reload_fields', this.init_fields );

To call it, you need to add parenthesis:

wp.hooks.addAction( 'wponion_reload_fields', this.init_fields() );

But, since it doesn't return anything, it wouldn't be correct to pass the result as an argument to wp.hooks.addAction.

And, in the base class, the method is called: init_fields(), but in the extended class it's called init_fileds().

Upvotes: 1

Related Questions