


This article brings you the basic use of JavaScript closure functions and solutions to problems encountered. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
I was always asked what a closure is during the interview. I didn’t really care about it before, let alone summarize it.
Closure is A function that can read the internal variables of other functions.
So, in essence, closure is a bridge connecting the inside of the function with the outside of the function.
(1) The most basic application of closure:
少废话,上代码 还是>的栗子,
function createComparisonFunction(propertyName) { return function(object1, object2) { var value1 = object1[propertyName]; var value2 = object2[propertyName]; if(value1 value2) { return 1; } else { return 0; } }; } var compare = createComparisonFunction("name"); var result = compare({ name: "Nicholas" }, { name: "Greg" });
Analysis:
(1) The closure function can access its external function
The anonymous function returned is a Closure function, the active object in this anonymous function that accesses the external function is the propertyName parameter. Because the external scope chain is included by this anonymous function (it can also be understood as: the compare function contains the active object and global variable object of the
createComparisonFunction() function), the returned anonymous function can always access its external propertyName and global variables.
(2) The external variables referenced by the closure will not be destroyed due to the destruction of the scope in which they are located.
Because the active object of the external function is referenced in the returned closure function, the active object in createComparisonFunction() (i.e. propertyName) will not be destroyed after createComparisonFunction() is executed. Because although createComparisonFunction will destroy the scope chain in its execution environment after execution, its active object is still referenced by the closure function and placed in the scope of the execution environment of the anonymous function
( 2) Side effects of closure
(1). Closure can only obtain the last value of any variable in the function
function createFunctions(){ var result = new Array(); for (var i=0; i <p>Principle:<br>Because of the scope chain of each function The active objects of the createFunctions() function are stored in them, so they all refer to the same variable i. When the createFunctions() function returns, the value of variable i is 10. At this time, each function refers to the same variable object that saves variable i, so the value of i inside each function is 10</p><p> Solution: </p><pre class="brush:php;toolbar:false">获取内部函数的对象result[i]时,使用匿名函数,并在匿名函数中再使用闭包函数,使得当前环境下的num被闭包函数函数调用,存储在作用域中不会被释放.
function createFunctions2(){ var result = new Array(); for(var i = 0 ; i <p>Principle: <br>Define an anonymous function and assign the result of the immediate execution of the anonymous function to the array. The anonymous function here has a parameter num, which is the value to be returned by the final function. When calling each anonymous function, we pass in the variable i. Since function parameters are passed by value, the current value of variable i is copied to parameter num. Inside this anonymous function, a closure accessing num is created and returned. This way, each function in the results array has its own copy of the num variable and can therefore return a different value. </p><p>(2). When an anonymous function is included outside the closure function, this points to the global </p><pre class="brush:php;toolbar:false"> var name = "The Window"; var object = { name: "My Object", getNameFunc: function () { return function () { //匿名函数执行具有全局性 return this.name; //this指向window }; } }; console.log(object.getNameFunc()()) // The Window
Principle:
Each function will automatically obtain two special variables when it is called : this and arguments. When the internal function
searches these two variables, it will only search until its active object, so the external this cannot be obtained. At this time, getNameFunc() returns an anonymous function, and the anonymous function is global. Therefore this points to the global window
Solution:
Save the this object in the external scope in a variable that the closure can access, so that the closure can access the object
var name2 = "The Window"; var object2 = { name:"My Object", getNameFunc:function(){ var that = this; //将外部函数的this保存在外部函数的活动对象中(函数中申明的变量中) return function (){ return that.name } } } console.log(object2.getNameFunc()()) //My Object
(3)
Disadvantages of closure
(1). Because a closure carries the scope of the function that contains it, it will occupy more memory than other functions. Excessive use of closures may lead to excessive memory usage
(2). Closures can only obtain the last value of any variable in the function, so pay attention to the writing
姧姧路
Posted 3 minutes ago
Read 7 times
It takes 12 minutes to read
I was always asked what a closure was during the interview. I didn’t really care about it before, let alone summarize it.
A closure
of other functions.
So, in essence, closure is a bridge connecting the inside of the function with the outside of the function.
(1) The most basic application of closure:
少废话,上代码 还是>的栗子,
function createComparisonFunction(propertyName) { return function(object1, object2) { var value1 = object1[propertyName]; var value2 = object2[propertyName]; if(value1 value2) { return 1; } else { return 0; } }; } var compare = createComparisonFunction("name"); var result = compare({ name: "Nicholas" }, { name: "Greg" });
Analysis:
(1) The closure function can access its external function
The anonymous function returned is a closure function , the active object in this anonymous function that accesses the external function is the propertyName parameter. Because the external scope chain is included by this anonymous function (it can also be understood as: the compare function contains the active object and global variable object of the
createComparisonFunction() function), the returned anonymous function can always access its external propertyName and global variables.
(2) The external variables referenced by the closure will not be destroyed due to the destruction of the scope in which they are located.
Because the active object of the external function is referenced in the returned closure function, the active object in createComparisonFunction() (i.e. propertyName) will not be destroyed after createComparisonFunction() is executed. Because although createComparisonFunction will destroy the scope chain in its execution environment after execution, its active object is still referenced by the closure function and placed in the scope of the execution environment of the anonymous function
(2) Side Effects of Closure
(1). Closure can only obtain the last value of any variable in the function
function createFunctions(){ var result = new Array(); for (var i=0; i <p>Principle:<br>Because each function The active objects of the createFunctions() function are stored in the scope chain, so they all refer to the same variable i. When the createFunctions() function returns, the value of variable i is 10. At this time, each function refers to the same variable object that saves variable i, so the value of i inside each function is 10</p><p> Solution: </p><pre class="brush:php;toolbar:false">获取内部函数的对象result[i]时,使用匿名函数,并在匿名函数中再使用闭包函数,使得当前环境下的num被闭包函数函数调用,存储在作用域中不会被释放.
function createFunctions2(){ var result = new Array(); for(var i = 0 ; i <p>Principle: <br>Define an anonymous function and assign the result of the immediate execution of the anonymous function to the array. The anonymous function here has a parameter num, which is the value to be returned by the final function. When calling each anonymous function, we pass in the variable i. Since function parameters are passed by value, the current value of variable i is copied to parameter num. Inside this anonymous function, a closure accessing num is created and returned. This way, each function in the results array has its own copy of the num variable and can therefore return a different value. </p><p>(2). When an anonymous function is included outside the closure function, this points to the global </p><pre class="brush:php;toolbar:false"> var name = "The Window"; var object = { name: "My Object", getNameFunc: function () { return function () { //匿名函数执行具有全局性 return this.name; //this指向window }; } }; console.log(object.getNameFunc()()) // The Window
Principle:
Each function will automatically obtain two special variables when it is called : this and arguments. When the internal function
searches these two variables, it will only search until its active object, so the external this cannot be obtained. At this time, getNameFunc() returns an anonymous function, and the anonymous function is global. Therefore this points to the global window
Solution:
Save the this object in the external scope in a variable that the closure can access, so that the closure can access the object
var name2 = "The Window"; var object2 = { name:"My Object", getNameFunc:function(){ var that = this; //将外部函数的this保存在外部函数的活动对象中(函数中申明的变量中) return function (){ return that.name } } } console.log(object2.getNameFunc()()) //My Object
(3)
Disadvantages of closure
(1). Because a closure carries the scope of the function that contains it, it will occupy more memory than other functions. Excessive use of closures may lead to excessive memory usage
(2). Closures can only obtain the last value of any variable in the function, so pay attention to the writing
Sort by time
Show more comments
The above is the detailed content of Basic use of JavaScript closure functions and solutions to problems encountered. For more information, please follow other related articles on the PHP Chinese website!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

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 Linux new version
SublimeText3 Linux latest version

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool