+ 5

setTimeout() and context "this"

I have simple object: var greetings = { hi: "Hello!", sayHi: function() { alert( this.hi ); } }; And I try to call method sayHi() by two different ways: 1. setTimeout(greetings.sayHi, 1000); 2. setTimeout(function() { greetings.sayHi(); }, 1000); The second one works. But why? Why the first setTimeout can't find context "this" ?

26th May 2017, 11:33 AM
Шыряй Баян
Шыряй Баян - avatar
3 odpowiedzi
+ 7
When you do it like in the first example, then you just pass the reference to the function in the object and not really to the object itself. You can use the bind function to tell the function that it should use the greetings object. And like that you can achieve the same result as if you call it inside a function. e.g: setTimeout(greetings.sayHi.bind(greetings), 1000);
26th May 2017, 11:40 AM
Tim G
Tim G - avatar
+ 8
@Tim you are too fast :(
26th May 2017, 11:42 AM
Maz
Maz - avatar
0
good question! Thanks
10th Jan 2018, 9:16 PM
Iaroslav Kalytiuk
Iaroslav Kalytiuk - avatar