search
HomeWeb Front-endJS TutorialJavaScript closures - variables and this object in closures

The mechanism of scope chaining in JavaScript can cause some side effects: a closure can only get the last value of any variable in the containing function. When using closures, we must pay attention to the variable value, because this is where mistakes often occur.

Below we use a very extreme example to illustrate this problem. In actual development, we generally do not write code like this. The code for this example is as follows:

function fn1(){
  var arr = new Array();
  //变量i保存在fn1作用域中
  for(var i = 0; i < 10;i++){
    arr[i] = function(){
      return i;
    }
  }
  return arr;
}
 
var values = fn1();
for(var i = 0; i < values.length;i++){
  //此时通过闭包来调用所有的函数,当输出i的时候会到上一级的作用域中查找,此时i的值是10,所以输出的都是10
  document.write(values[i]()+"<br>");
}

Executing the above code, we expected that 0-9 would be printed on the page, but 10 10s would actually be printed. Let's analyze this code: a function fn1 is created in the implementation code, an array object is created in the function, and a value is assigned to the array through a for loop. The loop is repeated 10 times, and each time an anonymous function is filled into the array and returned value, and finally returns an array object. Then get the reference to the fn1 function, and then output the values ​​in the array on the page through a loop.

The scope chain memory model of the above program is shown in the figure below:

JavaScript closures - variables and this object in closures

From the figure we can see that each loop in the fn1 function will generate an anonymous function, and they have their own scope chain , the high bits of their scope chains point to the global scope, the middle bits point to the outer fn1 scope, and the low bits point to their own scope.

After the execution of function fn1 is completed, the value of attribute i in the scope of fn1 is 10. At this time, the GC starts to recycle fn1, but it finds that there is an anonymous function pointing to the scope of fn1, so the scope of fn1 will not be recycled.

When the anonymous function is executed, it searches for the attribute i in its own space, but does not find it, so it goes to its superior fn1 scope to search. At this time, the i value in the fn1 scope is 10, so So the anonymous functions will all get the same i value: 10.

The way to solve this problem is to return an anonymous function in the anonymous function and save the current value through a variable. The code is as follows:

function fn1(){
  var arr = new Array();
   
  for(var i = 0; i < 10;i++){
    arr[i] = function(num){
      return function(){
        return num;
      }
    }(i);
     
  }
  return arr;
}
 
var values = fn1();
for(var i = 0; i < values.length;i++){
  //每一个fs都是在不同的作用域链中,num也是保存在不同的作用域中,所以输出0-9
  document.write(values[i]()+"<br>");
}

At this time, the value of num is stored in the scope of each anonymous function, and the value is exactly equal to the index value of each loop. In this way, every time the anonymous function is called, it will find the num attribute in its own space, and the values ​​​​of these num are different. At the same time, it will not look for the i attribute in the fn1 function scope.

The above code will generate the scope of 20 anonymous functions. If the code is not a simple return value, but some more complex operations, it will occupy a lot of memory space.

This object in closures

Using this object in closures will also cause some unexpected problems. The this object is bound at runtime based on the function's execution environment: for global functions, this object is window, and when the function is called as a method of an object, this is that object. In anonymous functions, this object usually points to window. Let's look at the following example:

var name = "window";
var person = {
  name : "Leon",
  age:22,
  say:function(){
    return function(){
      return this.name;
    }
  }
}
console.info(person.say()()); //控制台输出:window

In the above code, when we call the say() method of the person object, what is printed is not the name of the person object, but the global name "window". After person.say() is completed, the function call is completed. Before the function call ends, this points to person, but when the anonymous function is called, this points to window, so the result is "window" .

The way to solve this problem is to assign this reference to a temporary variable in the say() method. The code is as follows:

var name = "window";
var person = {
  name : "Leon",
  age:22,
  say:function(){
    var that = this;
    return function(){
      return that.name;
    }
  }
}
console.info(person.say()()); //控制台输出:Leon

The above is the JavaScript closure - the variables in the closure and the contents of this object. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


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
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use