+ 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" ?
3 Answers
+ 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);
+ 8
@Tim you are too fast :(
0
good question! Thanks