JavaScript "this" Pointer in Nested Functions
In JavaScript, the value of the "this" pointer can be confusing when working with nested functions. Contrary to expectations, calling a nested function can assign the "this" pointer to the global "window" object rather than the enclosing function.
Consider the following code:
<code class="javascript">var std_obj = { options: { rows: 0, cols: 0 }, activeEffect: "none", displayMe: function() { // this refers to std_obj if (this.activeEffect == "fade") { } var doSomeEffects = function() { // this unexpectedly refers to the window object if (this.activeEffect == "fade") { } }; doSomeEffects(); } }; std_obj.displayMe();</code>
In this scenario, when the nested function doSomeEffects is called, the "this" pointer points to the "window" object, even though it is declared within the scope of std_obj. This is because JavaScript determines the "this" pointer based on how the function is called.
In this case, doSomeEffects is called without a leading parent object, which results in the global object (usually the "window" object) being assigned to "this." To resolve this issue, three methods can be used:
Call the function with the call Method:
<code class="javascript">doSomeEffects.call(std_obj);</code>
Apply the function with the apply Method:
<code class="javascript">doSomeEffects.apply(std_obj, []);</code>
Create a Bound Function:
<code class="javascript">var boundDoSomeEffects = doSomeEffects.bind(std_obj); boundDoSomeEffects();</code>
The above is the detailed content of How to Preserve the \'this\' Pointer in Nested JavaScript Functions. For more information, please follow other related articles on the PHP Chinese website!