I was making a test case to show how ‘bind’ is necessary for a method to refer to its function in a callback.
But just when I thought I knew JS – the following code works fine – without requiring bind!
pretendThingConstructor = function (greeting) {
this.greeting = greeting;
this.sayHello = function() {
console.log(this.greeting);
};
}
var pretend_thing = new pretendThingConstructor('hello world');
pretend_thing.sayHello();
setTimeout(function() {
pretend_thing.sayHello()
}, 3000);
When I run it – via node, phantomjs, or another JS environment – it works. ‘hello world’ is printed twice.
I expected the second ‘hello world’ – the one ran after the timout – to fail, as ‘this’ would refer to the event, rather than the object. But it works. Why is this?
The
thischanges depending on how your call the function. If you specify a base object, it will refer to that instead:Here
pretend_thingis that base object and thereforethisstill refers to that object. On the other hand, if you had:Here
thisshould refer towindowobject instead.You can confirm it by putting:
Inside your
sayHellofunction. It will printtruein both cases.will output:
whereas:
outputs: