2

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();
woutr_be
  • 9,532
  • 24
  • 79
  • 129
  • You didn't set the preprocessor on CodePen, so it's trying to use ES6 features which may be missing in your browser. Set the JavaScript preprocessor to Babel – CodingIntrigue Sep 22 '15 at 07:23
  • @RGraham While that works in CodePen, I'm running this in a Node application. (v4.0.0) – woutr_be Sep 22 '15 at 07:25
  • Sorry, I thought you were talking about the demo, I see the tag now. Perhaps Babel can't transpile this and NodeJS exhibiting correct behavior. Good Question - I would just remove your demo :) – CodingIntrigue Sep 22 '15 at 07:30
  • @RGraham I'm not sure why the other answer was removed, but using arrow functions actually solved the problem. `return new Promise((resolve, reject) => { super.test(); })` – woutr_be Sep 22 '15 at 07:32
  • I think they panicked because of my incorrect comment. But the answer is correct. *Why* that works though when Babel doesn't see it that way is the question. – CodingIntrigue Sep 22 '15 at 07:33
  • 2
    I deleted it because it was only semi-correct. Changing the preprocessor indeed solved it in codepen. Do you have any source on the scope of `super` in ES6? I can't really find anything with a definite answer. – ralh Sep 22 '15 at 07:39
  • 3
    @ralh [Found it](https://esdiscuss.org/topic/specifics-of-class-and-super) (down atm, Google for cached version) Babel is wrong, Node's implementation (and your answer) is correct – CodingIntrigue Sep 22 '15 at 10:23

1 Answers1

3

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

ralh
  • 2,514
  • 1
  • 13
  • 19