闭包

通过闭包访问到了局部变量text

function greeting(name) {
    var text = 'Hello ' + name; // local variable
    // 每次调用时,产生闭包,并返回内部函数对象给调用者
    return function () {
        console.log(text);
        return text
    }
}

var sayHello = greeting("Closure");
sayHello()  // 通过闭包访问到了局部变量text

let和闭包解决this丢失

for (let i = 0; i <= 5; i++) {//let是关键
    (function () {//包一层自执行行数,带参数
        setTimeout(function (timer) {
            console.log(i)
        }, i * 1000)
    })(i)
}

使用闭包对外暴露方法

(function () {
    const a = 10;
    const b = 20;

    function add(num1, num2) {
        num1 = !!num1 ? num1 : a;
        num2 = !!num2 ? num2 : b;

        return num1 + num2;
    }

    this.add = add;//方法add被作为一个闭包,对外暴露了一个公共方法
})();

console.log(add(10, 20));

高级闭包demo

function newClosure(someNum, someRef) {
   // Local variables that end up within closure
   let num = someNum;
   let anArray = [1, 2, 3];
   let ref = someRef;
   return function (x) {
       num += x;
       anArray.push(num);
       console.log('num: ' + num +
           '\nanArray ' + anArray.toString() +
           '\nref.someVar ' + ref.someVar);
   }
}

closure1 = newClosure(40, {someVar: 'closure 1'});

closure1(5);//等同于return
closure1(5);//上次执行的结果还保存着哦


你可能感兴趣的:(闭包)