Home  >  Article  >  Web Front-end  >  Code examples for Javascript closures

Code examples for Javascript closures

不言
不言forward
2019-03-05 13:51:502050browse

This article brings you code examples about Javascript closures. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Closure

When the inner function is saved to the outside, a closure will be generated. Closure will cause the original scope chain not to be released, causing memory leaks

//内部的函数被返回到外部,必然形成闭包
function a(){
function b(){
var b = 234;
console.log(a);
}
var a = 123;
return b;
}
var demo = a();
demo(); // -->123
function test1(){
var num = 100;
function test2(){
num ++;
console.log(num);
}
return test2;
}
var demo1 = test1();
demo1();  //101
demo1();  //102
//
function test(){
            var arr = [];
            for(var i = 0; i < 10; i++){//当i = 10的时候循环停止
                arr[i] = function(){ //arr的每一位都是一个函数
                    console.log(i);//虽然函数已经定义,但未执行
                }
            }
            return arr;
        }
        var myArr = test();
        for(var i = 0; i < myArr.length; i++ ){
            myArr[i]();
        }

When the last function is executed, i

AO{
i = 10;
}

in the AO of test will be called. Solution: execute the function immediately

function test() {
            var arr = [];
            for(var i = 0; i < 10; i++) {
                (function(j) {
                    arr[j] = function() {
                        console.log(j);
                    }
                }(i))
            }
            return arr;
        }
        var myArr = test();
        for(var i = 0; i < myArr.length; i++) {
            myArr[i]();
        }

1. Implement public variables

eg: function accumulator

function add(){
var count = 0;
function demo(){
count ++ ;
console.log(count);
}
return demo;
}
var counter = add();
counter();

2. Can be cached

eg:eater

function test2(){
var food = &#39;apple&#39;;
var obj = {
eatFood : function(){
if(food != ""){
console.log("I am eatting " + food);
food = &#39;&#39;;
}else{
console.log("There is nothing! empty!");
}
},
pushFood : function(myFood){
food = myFood;
}
}
return obj;
}
var obj = test2();
obj.eatFood();
obj.eatFood();
obj.pushFood(&#39;banana&#39;);
obj.eatFood();

3 .Encapsulation and attribute privatization can be achieved.

eg: Person();

The above is the detailed content of Code examples for Javascript closures. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete