In the below piece of code, when sayAysncHi()
is called on gs
object, what is this
bound to ? My understanding is that this
is bound to the thing to the left of the dot (.
) operator which in this case should be the GreetingService
object gs
. However in this case the this.name
inside the sayAsyncHi
fn is coming in a undefined
- why is this so?
// file greeting_service.js
function GreetingService(name) {
this.name = name;
this.sayHi = function () {
console.log(this);
console.log(`Hi ${this.name}!`);
}
this.sayAsyncHi = function () {
setTimeout(function (params) {
console.log(this);
console.log(`Hi ${this.name}!`);
},2000);
}
this.sayBye = function () {
console.log(`Bye ${this.name}!`);
}
}
var gs = new GreetingService('Jon');
gs.sayHi(); // Hello Jon!
gs.sayAsyncHi(); // Hello undefined!
Output on running node greeting_service.js
( nodejs 6)
GreetingService {
name: 'Jon',
sayHi: [Function],
sayAsyncHi: [Function],
sayBye: [Function] }
Hi Jon!
Timeout {
_called: true,
_idleTimeout: 2000,
_idlePrev: null,
_idleNext: null,
_idleStart: 389,
_onTimeout: [Function],
_repeat: null }
Hi undefined!
PS: with ES6 Arrow function the binding is correct as expected for the above Async call