Home > Web Front-end > JS Tutorial > body text

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

DDD
Release: 2024-10-19 06:52:01
Original
248 people have browsed it

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>
Copy after login

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>
    Copy after login
  2. Apply the function with the apply Method:

    <code class="javascript">doSomeEffects.apply(std_obj, []);</code>
    Copy after login
  3. Create a Bound Function:

    <code class="javascript">var boundDoSomeEffects = doSomeEffects.bind(std_obj);
    boundDoSomeEffects();</code>
    Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!