-1

So, I recently had a pretty weird problem when developing a library, safe_children.

When I was writing the examples, I decided to try making it like this:

var child = new Child('otherFile.js', 3 * 60);
child.loadScript()
  .then(child.spawn);

This code doesn't work. this points to something I couldn't find out. However, this piece of code works:

var child = new Child('otherFile.js', 3 * 60);
child.loadScript()
  .then(function(){
    child.spawn();
  });

Anyone knows why? What is this in this context? Thanks!

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Gabriel Tomitsuka
  • 1,121
  • 10
  • 24

1 Answers1

3

Your issue here has nothing to do with promises.

You are passing in child.spawn, which is nothing more than a function. Your promise has no way to know that it belongs to child, so all it can do is call it. Therefore, this will most likely either be null, undefined, or the window object.

You can see the same behavior by doing:

var sp = child.spawn;
sp();    // <---- `this` is not `child` here

You can get around this by doing:

.then(child.spawn.bind(child));

or by doing what you've already done.

JLRishe
  • 99,490
  • 19
  • 131
  • 169