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?
It is used with inner functions. As you know, you can have functions in object constructors and there can be functions inside functions. If you see the code below.
When you call getArea(), you will get area according to radius 10. Although you are calling changeRadius() but inside inner function changeRadius, this starts to point to global object instead of the object you created. You use var
self=this construct
to get around here.so in order to get around this situation we can have the following changes.
It is so that when
this
changes, you still have a reference tothis
at the point in the code you need.It's useful if there are functions inside a function, such that code in those nested functions needs access to the value of
this
from the outer context.Because
this
is established anew for every function call, without stashing the outerthis
in a variable there'd be no way to reference it at all from the inner function.That is often used for callback methods, where the scope would be different when the callback runs.
Example:
This is used to save reference to
this
. Later in the code there's an AJAX call with a callback (for example). So, inside of that callbackthis
is not the same as outside. That's why people back up "outer"this
to a variable.I personally like to use this form:
Looks funny :)
By the way, CoffeeScript, which is a kind of "javascript done right", has a fix for this as well.
It has two forms for function definition, thin arrow and fat arrow. Thin arrow behaves exactly like in javascript, and fat arrow automatically binds
this
to a value from outer context.So, this coffeescript
gets transformed to this javascript
Cool, isn't it?
The usual reason is that the code contains a closure that will get called at some later time, and the author wants to make sure the closure has access to the current
this
. Example:Here's code that people frequently write incorrectly, like this:
Here's that
var me = this;
applied to it:This comes about because in JavaScript,
this
is defined entirely by how a function is called, not where the function is defined.More reading (disclosure: both are links to my blog):
this