Javascript SetInterval With Context (javascriptisawesome.blogspot.com) 3 points by jQueryIsAwesome 14y ago ↗ HN
[–] igorw 14y ago ↗ The reason why `this` is set to the window is because of the way the `this` keyword is bound in JavaScript. It is bound at call time.If at call time it is being called on an object, it will have the value of that object. Otherwise it will have the value of window. var obj = { f: function () { return this; } }; // returns the object obj.f() // returns window var f = obj.f; f(); What is happening here is that the setTimeout() calls the lambda at some later point, and it's no longer in the context of the object.An alternate fix for the issue would be: var obj = (function () { var that = {}; that.doSomethingLater = function () { setTimeout(function () { console.log(that); }, 1000); }; return that; })(); obj.doSomethingLater(); An article on the subject (that also talks about call and apply): http://www.robertsosinski.com/2009/04/28/binding-scope-in-ja...
1 comment
[ 27.5 ms ] story [ 309 ms ] threadIf at call time it is being called on an object, it will have the value of that object. Otherwise it will have the value of window.
What is happening here is that the setTimeout() calls the lambda at some later point, and it's no longer in the context of the object.An alternate fix for the issue would be:
An article on the subject (that also talks about call and apply): http://www.robertsosinski.com/2009/04/28/binding-scope-in-ja...