javascript - What is the use of closures in practical development?
PHPz
PHPz 2017-05-16 13:35:00
0
9
944

After watching the explanation of the function of closure in the video, I still don’t understand it. For example, the code in the screenshot can be implemented by adding a passline parameter to the cmp function. There is no need to use closure.

Who can give a better example to illustrate the role of closure?

PHPz
PHPz

学习是最好的投资!

reply all(9)
过去多啦不再A梦

Extend the life cycle of local variables and encapsulate private variables

2. 延续局部变量的寿命
img 对象经常用于进行数据上报,如下所示:
var report = function( src ){
    var img = new Image();
    img.src = src;
};
report( 'http://xxx.com/getUserInfo' );
但是通过查询后台的记录我们得知,因为一些低版本浏览器的实现存在 bug,在这些浏览器
下使用 report 函数进行数据上报会丢失 30%左右的数据,也就是说, report 函数并不是每一次
都成功发起了 HTTP 请求。丢失数据的原因是 img 是 report 函数中的局部变量,当 report 函数的
调用结束后, img 局部变量随即被销毁,而此时或许还没来得及发出 HTTP 请求,所以此次请求
就会丢失掉。
现在我们把 img 变量用闭包封闭起来,便能解决请求丢失的问题:
var report = (function(){
    var imgs = [];
    return function( src ){
        var img = new Image();
        imgs.push( img );
        img.src = src;
    }
})();
伊谢尔伦

Save variables. Most of the time I use it to replace global variables to avoid variable pollution

巴扎黑

The problem solved by closure: Based on JS's lexical scope rule, its access is to search the scope upwards until global scope. If you want to directly access a certain scope, you can use closures.

function foo(){
var a = 1;
function bar(){
    console.log(a);
}
return bar;
}
var baz = foo();
baz();

The lexical scope of bar can access the internal scope of foo. After foo is executed, it returns bar and finally assigns it to baz, can obtain and access the internal scope of foo, but the identifier is different. bar词法作用域可以访问foo内部作用域,foo执行后返回bar,最后赋值给baz,可以获取并访问foo内部作用域,只是标识符不同而已。
该代码就使用了闭包,可以说写JSThis code uses closures. It can be said that closures can be seen everywhere when writing code. Another benefit of using closures is that the referenced scope will not be garbage collected. Of course, unreasonable use will consume memory

.

Closures are used to add variables (if you can access a certain scope, you can naturally add variables) or extend its life cycle

(when the scope is referenced, it will naturally be extended)

for (var i = 0; i < 5; i++){
    setTimeout(function(){
    console.log(i)},i * 1000)
}    

for (var i = 0; i < 5; i++){
    (function (i) {
    setTimeout(function(){
    console.log(i)},i * 1000)
    })(i)    
}
i变量(变量和函数声明都提升了)。
第二个循环是定义了几个立即执行函数,又传递了i值,故每个iThe first loop declares several functions, and the shared global
values ​​have their own scopes. This is a better example, closure + loop, but this one is special, the closure accesses its own scope.

Of course, the module that best embodies the idea of ​​closure is the module, which returns a method, which effectively introduces a scope.

Closure: It is a way to obtain and access a certain scope, which can be accessed externally or within itself.

🎜
Ty80

The two biggest functions

  1. Read function internal variables

  2. Always keep variable values ​​in memory

I won’t go into details about the first one, but look at the second one for an example

function f1(){
    var n=999;
    nAdd=function(){n+=1}
    function f2(){
      alert(n);
    }
    return f2;
  }
  var result=f1();
  result(); // 999
  nAdd();
  result(); // 1000   

result is actually the closure f2 function. It was run twice, the first time the value was 999, the second time the value was 1000. This proves that the local variable n in function f1 is always stored in memory and is not automatically cleared after f1 is called.
Why is this happening? The reason is that f1 is the parent function of f2, and f2 is assigned to a global variable, which causes f2 to always be in memory, and the existence of f2 depends on f1, so f1 is always in memory and will not be deleted after the call is completed. , recycled by the garbage collection mechanism (garbage collection).
Another thing worth noting in this code is the line "nAdd=function(){n+=1}". First of all, the var keyword is not used before nAdd, so nAdd is a global variable, not a local variable. Secondly, the value of nAdd is an anonymous function, and this anonymous function itself is also a closure, so nAdd is equivalent to a setter, which can operate on local variables inside the function from outside the function

  • Manage private variables and private methods, and encapsulate changes to variables (state) in a safe environment

  • Encapsulate the code into a closure form and wait for it to be used when the time is right, such as implementing currying and de-currying

  • Things to note:

    • Because some resources within the closure cannot be automatically released, it is easy to cause memory leaks. The solution is to delete all unused local variables before exiting the function.

    • The closure will change the value of the variable inside the parent function outside the parent function. Therefore, if you use the parent function as an object, the closure as its public method, and the internal variables as its private value, you must be careful not to Feel free to change the value of the variable inside the parent function.

世界只因有你

If I say, set_passLine is actually a function of two parameters, can you accept it?

def set_passLine(passline)(val): # 虽然这不符合语法
    pass

This sum function

def set_passLine(passline,val):
    pass

are functionally equivalent, but the former does not need to be called with all parameters at once.

In addition, the first way of writing can achieve the same function as a class:

def set_passLine(passline):
    def cmp(val):
        pass
    def resetPassLine(newPassline):
        passline=newPassline
        pass
    return (cmp,resetPassLine)

Although these are different implementations of the same functionality. But people are increasingly finding that functional programming is better than other methods. Better means better and clearer in terms of code size (but the requirements for programmers are getting higher and higher).

Give me a link, but I wrote it in js: http://zonxin.github.io/post/...

P.S.
Object-oriented programming is to regard all "objects" as objects. Programming is to use objects to simulate the behavior of "objects", that is, to simulate the operation of a certain "world".
Functional programming only cares about the initial state of the "object" and the final state of the "object" after passing through the function, without caring about the process. Programming is to deal with the composition of these functions.

滿天的星座

I have always understood it this way: protect internal variables and operate through exposed APIs.

var name="meimei"
function Private(){
    var name = "leilei";
    return {
        getName:function(){
            console.log(name)
        },
        setName:function(val){
            name = val;
        }
    }
}
var private = Private();
private.getName()//"leilei"
private.setName("xiaoming")
private.getName()//"xiaoming"
name//"meimei"
//通过暴漏API来操作内部变量。
jquery:
(function(){
...
    window.$=window.jquery=window.jQuery=...
})
//一个匿名自执行函数通过window暴漏jquery,内部变量不会受到其他全局变量的污染,只能通过$的API进行操作。

The above is my personal understanding

Ty80

Avoid variable pollution, but if it is in ES6, use let and const to solve this problem

大家讲道理

At the elementary level
I only know that 1. You can access local variables
2. They can always be saved in memory

So the frequency of use should not be too high, as it may cause memory leaks

PHPzhong

Answer something that impressed me 偏函数

function logger(logType){
    return console.log.bind(console, logType); 
}

var info = logger('[INFO]'); 
var error = logger('[ERROR]'); 

info('this is an info'); 
// => 
// [INFO] this is an info

error('this is an error'); 
// => 
// [ERROR] this is an error
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template