Home  >  Article  >  Web Front-end  >  How to Preserve the \"this\" Pointer in Nested JavaScript Functions

How to Preserve the \"this\" Pointer in Nested JavaScript Functions

DDD
DDDOriginal
2024-10-19 06:52:01249browse

How to Preserve the

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:

  1. Call the function with the call Method:

    <code class="javascript">doSomeEffects.call(std_obj);</code>
  2. Apply the function with the apply Method:

    <code class="javascript">doSomeEffects.apply(std_obj, []);</code>
  3. 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn