0

Here's working code sample:

function Drum(){
  this.noise = 'boom';
  this.duration = 1000;
  this.goBoom = function(){console.log(this.noise)};
}
var drum = new Drum();
setInterval(drum.goBoom.bind(drum), drum.duration);

If I remove .bind(drum) part from this code instead of 'boom' I'll get 'undefined' in console. What's the reason of such behavior since typeof drum.goBoom returns 'function' ?

Anton
  • 939
  • 1
  • 12
  • 22
  • 2
    Just to be clear, it's `noise` that is actually undefined in your example. Because `this` doesn't reference the Drum instance (I think it's actually the window instance it will reference). – musefan Nov 07 '17 at 11:45
  • yep, to Timeout object – Anton Nov 07 '17 at 12:24

2 Answers2

2

since typeof drum.goBoom returns 'function'

This is actually irrelevant. It's value of this keyword which is important in here. You are passing a function reference by passing drum.goBoom as the first argument of the setInterval function, without using bind for setting the this keyword's value manually the setInterval calls the function with global object as it's this value (context) which doesn't have noise keyword, so console.log logs undefined.

undefined
  • 136,817
  • 15
  • 158
  • 186
1

Taking a look at the documentation for bind.

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

If you omit the bind(drum) then this within the call back will be something other than the drum object you want.

phuzi
  • 8,111
  • 3
  • 24
  • 43