Understanding "this" Within Anonymous Function In Javascript
Solution 1:
this and scope have almost nothing to do with each other. In JavaScript, this is usually set by how a function is called, not where it's defined. (There are two exceptions to that rule, I'll mention them below.)
So when you're calling A, you're setting what this will be during the call (largely implicitly). When you do this:
A();
...you're calling A without doing anything explicit to set what this should be; as a result, you're implicitly calling it with this set to undefined, because your code is in strict mode. (If it were in loose mode, you'd be calling it with this set to a reference to the global object.) It's also worth noting that you're resolving the identifier A via the context created by the call to your anonymous function, which contains A and B as (effectively) variables.
But here:
this.A();
...you're calling A as part of an expression getting the function reference from an object property (A; note that this is a different meaning for A, but that both the property and the context variable refer to the same function). The act of doing that calls A with this set to a reference to the object you got the property from.
That's why you see two different values for this in A.
The exceptions to the "this is set by how you call it" rule are:
ES6's "arrow" functions, which inherit
thisfrom the context (not scope) where they're created.ES5's "bound" functions (the result of calling
.bindon a function reference), which havethisbaked into them by the.bindcall and so always see the same value forthis.
Solution 2:
Usually, this, in a function, is bound to the object on which you called that function.
In your example:
- You call
myModule.B(),thisequals tomyModule, as you can see from the output:{ B: [Function: B], A: [Function: A] } - Then, inside the
tryblock you callA()without an object, herethisisundefinedbecause you're running in strict mode, otherwise it would point to the global object, which iswindowin a browser orglobalin node - Finally, the last call is
this.A(), here you're basically passing your currentthis(myModule) to the function, so it will bemyModule.
The whole this binding is affected only by the way you call a function.
Post a Comment for "Understanding "this" Within Anonymous Function In Javascript"