0

I have a typical call hierarchy

class A
{
   mirm(){
     //stuff here
   }
}

class B extends A
{
   constructor(){
     //obtain a promise
     promise().then(this.setUp)
   }

   setUp(){
    super.mirm();
   }
}

Could it be that the promise might be doing something to the scope? I would actually expect for you to be able to do something like this.mirm() from the setUp function since it should just follow the prototype chain. What gives? I am compiling with babel and have es2015 as target.

naughty boy
  • 2,089
  • 3
  • 18
  • 28
  • You [shouldn't do this](http://stackoverflow.com/q/24398699/1048572) anyway .-) – Bergi Apr 17 '16 at 21:37
  • Well I was not returning a promise, but the logic of not executing any tasks inside the constructor does make sense. I have changed it now, however the problem would have persisted regardless so my question still holds, thanks though. – naughty boy Apr 17 '16 at 22:59
  • unless you have a better design pattern? – naughty boy Apr 17 '16 at 23:00

1 Answers1

3

Passing this.setUp detaches the current context object from the function reference when it gets invoked, therefore the this in the super's method is confused about where to look

Consider wrapping it instead

// arrow function preserves context
foo.then(() => this.setUp());
// OR
// binding it to explicitly give context
foo.then(this.setUp.bind(this));
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • Yep, arrow functions did the trick for me, I read they have lexical scope and was just coming back to answer my question. I was unaware of the second approach though, thanks. – naughty boy Apr 17 '16 at 21:33
  • `super` is functioning well in unbound functions, it looks up `mirm` correctly. The problem is only that it calls it on the wrong `this`, so `mirm` itself will be confused. – Bergi Apr 17 '16 at 21:36
  • @Bergi Yeah, I'll reword it – Paul S. Apr 17 '16 at 21:42