The interviewer will ask a question of the closure -----

When looking for a job interview, the interviewer to ask you one kind of problem with the same good will discuss, that is the closure of this issue .

Under normal circumstances would ask:

What is closure?

Closures what features?

Closures have any effect on the page?

What are the advantages and disadvantages closure?

...............

So, now we come to the plate a closure!

 

What is closure:

Closure is the use of nested scopes, the original local variables, evolve into the environment free private variables.

Closed Principle package:

Use nested scopes, triggering computer's garbage collection mechanism , the variable originally to be removed temporarily saved, you can continue to use.

Garbage collection:

The data to be deleted, temporarily stored in a temporary space, not deleted immediately, if need to use again, you can find this data directly to continue to use, such as no more use to go clear out.

Application package closure:

1. Asynchronous cycle:

var ali = document.querySelectorAll("li");

//第一种
for(var i=0;i<ali.length;i++){
    (function(index){
        ali[index].onclick = function(){
            console.log(index);
        }
    })(i)
}

//第二种
for(var i=0;i<ali.length;i++){
    ali[i].onclick = (function(index){
        return function(){
            console.log(index);
        }
    })(i);
}

//第三种
for(let i=0;i<ali.length;i++){
    ali[i].onclick = function(){
        console.log(i);
    }
}

2. The timer callback function

setTieout(fn("hello"),5000);
function fn(str){
    return function(){
        console.log(str);
    }
}

3. Repeat the external variables inside a function

function fn(){
    var a =10;
    return function(){
        console.log(a++)
    }
}
var  f  = fn();
f();
f();
f();

 Characteristics closure package:

The closure is the scope of the internal and external connecting bridge

advantage:

1. You can save data to be deleted up and continue to use, very convenient

2. The data may be external to the internal operation of the function

Disadvantages:

1. Because the data to be deleted, not deleted but it continues to exist, it will account for memory, performance is good.

2. The external data may change inside.

Guess you like

Origin www.cnblogs.com/musen123/p/11609642.html