I often see this in code: var me = this;
. Why is that? Is there some performance gain if I reference 'this' in local variable?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- void before promise syntax
- Keeping track of variable instances
- Can php detect if javascript is on or not?
That is for closure scope. Look at the difference in these two jQuery plugins:
The problem is with
setInterval
. When the function insetInterval
gets called, it starts a new chain of execution, andthis
in that chain is bound towindow
. In the closure example, we keep a reference to the jQuery object we apply the plugin to in thejQueryMonad
(orme
in your code). This way, we can keep our scope correct in javascript.In the second example,
jQuery.proxy
handles that for you.This is to solve the issues when javascript binds
this
at execution time, instead of creation time.IMO it's unusual you'd see that on its own--it's a construct almost always used when there are closures involved to avoid JS's treatment of the
this
value, evaluated during execution, not declaration.