tag:blogger.com,1999:blog-8729407087018325447.post2843825742390430900..comments2024-03-06T14:41:16.291-05:00Comments on Kirk's UI Dev Blog: scope-a-dopeKirk Ishttp://www.blogger.com/profile/15605658292036699663noreply@blogger.comBlogger3125tag:blogger.com,1999:blog-8729407087018325447.post-7523366552060470202011-11-09T12:12:08.839-05:002011-11-09T12:12:08.839-05:00Thanks for clarifying Jeremy! I almost want to see...Thanks for clarifying Jeremy! I almost want to see an article "Use of 'this' Considered Harmful?"Kirk Ishttps://www.blogger.com/profile/15605658292036699663noreply@blogger.comtag:blogger.com,1999:blog-8729407087018325447.post-22173358606748440992011-11-08T17:23:04.559-05:002011-11-08T17:23:04.559-05:00Now, as for the Javascript "this" pointe...Now, as for the Javascript "this" pointer, it is insane. It is always bound at the time it is CALLED, never at the time it is defined. So you have to be sure, when you pass functions around, that the code you are passing them to calls it "correctly", or else terrible things happen.<br /><br />var func = function() { console.log(this); };<br />var x = {};<br />var y = {method:func};<br /><br />func(); // "this" is the "global" object (generally window) <br />new func(); // "this" is a newly constructed object, which this expression returns<br />y.method(); // "this" is y<br />func.apply(x); // "this" is x<br /><br />CreateDelegate is simply a way of making sure that no matter how the code you don't control calls the function, the "this" pointer always points at the same thing. You can pass in any random javascript object you like.Jeremyhttps://www.blogger.com/profile/03965288220543555460noreply@blogger.comtag:blogger.com,1999:blog-8729407087018325447.post-20859846953333883372011-11-08T16:47:50.532-05:002011-11-08T16:47:50.532-05:00When you create a closure in JS (and most imperati...When you create a closure in JS (and most imperative languages where you can create closures), that closure has as its context the scope that it was created in. So code like this:<br /><br />var x = 5;<br />(function() { x = 12; })();<br />console.log(x);<br /><br />prints 12.Jeremyhttps://www.blogger.com/profile/03965288220543555460noreply@blogger.com