Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I just use 'this' as much as possible. It helps me keep track of which object/scope 'this' is referencing. Creating a second reference to the object/scope referenced by 'this' doesn't really change anything.

Something I also find helpful is reminding myself that I'm not just writing a function, but a method for the current object (referenced by 'this').



Yes it does change things. You're not understanding that "this" is a keyword, not a variable reference, and as such, it is not treated the same in closures. The "this" KEYWORD is dynamically bound at runtime, not lexically scoped like every other variable. It is impossible to close over "this", yet it's what you usually want to do. That is why people use ugly work-arounds like "var me = this;". So "this" is a pitfall and language design flaw that traps many JavaScript programmers (even experienced ones) into thinking they're writing correct code that looks like it does one thing, which actually does a totally (and sometimes subtly) different thing.


The article is about 'this', not about creating closures.

I agree that in the case where you're creating a closure, you need to create a reference to the scope referenced by 'this' in order to 'enclose' it, however, that doesn't make it a best practice, all the time, as many responses are suggesting.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: