Understanding "this" In Javascript
Solution 1:
The first one doesn't work because when each function's this
depends on how it was called.
First you do myObject.double2()
and so this = myObject
. But inside double2
, you call helper()
by itself and there is no object you're calling it under (it's not myObject.helper()
). So this
defaults to the global
object (or window
object in a browser).
In the second example, you "capture" a reference to myObject
(that=this=myObject
) and so that.value=myObject.value
.
Solution 2:
I think this link would greatly help you in understanding the differences of object and private members in Javascript to tackle your problem, please take a look at the Private section. Hope it helps!
Solution 3:
Mozilla has some good reading on this. If you want this to work without assigning this
to that
, you can always use call.
Example: jsfiddle.net/5azde/
Solution 4:
And you can always remember this:
When a function of an object is called, the object will be passed as this value(as the case 'add' and 'increment' function which belong to 'window' and 'myObject' separately). And if the function doesn't belong to any objects, window(or global) will be passed as this value.(as the case with function helper in your sample code).
And I'm glad to see a pure js question. No jQuery, No css, No dom selector. haha.
May it helps. :-)
Post a Comment for "Understanding "this" In Javascript"