+ 3

Explain the Output

My Question is that when i using the setimeout to calling the method directly it says undefined.but when i use function inside setimeout it gives the output WHY? let user = { firstName: "John", sayHi:function() { console.log(`Hello, ${this.firstName}!`); } }; setTimeout(user.sayHi, 1000); setTimeout(function(){ user.sayHi() },1000);

28th Jul 2020, 2:49 PM
Samir Singh
Samir Singh - avatar
1 Respuesta
+ 3
It’s all about context. when you invoke setTimeout(), you are actually invoking window.setTimeout(). as a result, the anonymous function being passed to setTimeout() is being defined in the context of the window object, which has no "firstName" property. alternatively, you can use the bind() method to pass in the proper reference: let user = { firstName: "John", sayHi:function() { console.log(`Hello, ${this.firstName}!`); } }; setTimeout(user.sayHi.bind(user), 1000); setTimeout(function(){ user.sayHi() },1000); the bind method creates a new function with the "this" value pre-filled.
28th Jul 2020, 3:31 PM
MO ELomari
MO ELomari - avatar