woutr_be
woutr_be

Reputation: 9722

Calling super methods inside separate scope

I'm trying to call a super method from inside a different scope, but this doesn't appear to be working.

'use strict';

class One {
    test() {
        console.log('test');
    }
 }

class Two extends One {
    hi() {
        super.test();
    }
    hello() {
        var msg = 'test';
        return new Promise(function(resolve, reject) {
             console.log(msg);
             super.test();
        });
    }
}

var two = new Two();
two.hi();
two.hello();

Upvotes: 2

Views: 315

Answers (1)

ralh
ralh

Reputation: 2564

Apparently, in Babel it works right out of the box. In node though, it appears that in that anonymous function, this is no longer bound to the two object and super is not available then. You can use a fat arrow to bind this to the scope of the anonymous function:

return new Promise((resolve, reject) => {
    console.log('Message: ', msg);
    super.test();
});

If you're not familiar with the concept of fat arrows and/or this scope, this is a good read: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Upvotes: 3

Related Questions