javascript closure

巴扎黑
Release: 2016-12-10 09:16:23
Original
1143 people have browsed it

Concept:

A closure is a function that can read the internal variables of other functions.

Create a closure method:

Create another function inside a function, and access the local variables of this function through another function.

Js code

function box(){ var user ='Zhu'; return function(){ return user; } } var b = box(); console.log(b()) console.log(box()())
Copy after login




Advantages of using closures:
Local variables can reside in memory to avoid global variable pollution.
Accumulate local variables through closures:

Js code

function func(){ var num=100; incr=function(){// 未使用关键字var , 该函数为全局 num+=1; return num; } var m1= function(){ console.log(num) } return m1; } var m1 = func(); m1();//100 console.log(incr())//101。。通过全局函数操作局部变量 m1();//101
Copy after login





Disadvantages:
Since the local variable resources returned by the scope in the closure will not be destroyed and recycled immediately, it is easy to transition to using closures Resulting in performance degradation.


Related labels:
source:php.cn
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
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!