JavaScript闭包读书笔记

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/asdf_123123/article/details/89285300

JavaScript闭包读书笔记

// 作用域链:一个对象列表。
// 每次调用javascript函数的时候,都会为其创建一个对象来保存局部变量,并把这个对象添加到作用域链中,当函数返回的时候,再将这个绑定的作用域链删除。
// 闭包可以捕捉到局部变量和参数,并且一直保存下来
var scope = "global scope";
function checkscope() {
    var scope = "local scope";
    function f() { return scope;}
    return f();
}
checkscope() // local scope

var scope = "global scope";
function checkscope() {
    // body...
    var scope = "local scope";
    function f() {return scope;}
    return f;
}
checkscope()    // 返回函数内嵌套的对象
checkscope()()  // local scope
// 作用域链是函数定义的时候创建的,嵌套的函数f()定义在作用域链里,因此其中的scope是局部变量

// 闭包中访问外部函数的this和arguments
var scope = "global scope";
function checkscope(){
    var scope = "local scope";
    // this是javasctipt的关键字,不是变量
    // 将this转换为变量,以便嵌套的函数能够访问它
    var self = this;
    function f(){
        return self.scope;
    }
    return f();
}
checkscope() 	// global scope

// 计数器
// 外部函数返回后,其他任何代码都无法访问counter变量,只有内部函数才能访问到
var uniqueInteger = (function(){
    var counter = 0;
    return function(){
        return counter++;
    }
}())

// 多个嵌套函数共享一个作用域链
var uniqueInteger = function(){
    var counter = 0;
    return {
        count: function(){return counter++;},
        reset: function(){return counter=0;}
    }
}
// a,b不会互相影响
a = uniqueInteger()
b = uniqueInteger()
a.count()       // 0
a.count()       // 1
b.count()       // 0
a.reset()       // 0
a.count()       // 0

// 定义了10个闭包,并存储到一个数组中,这写闭包都是在同一个函数中定义的,因此共享变量i,因此当变量返回时,i的值为10,所有变量都共享这个i的值,所以,所有变量的返回值最终都是10
function constfunc(){
    var funcs = [];
    for (var i=0; i<10; i++){
        funcs[i] = function(){return i;}
    }
    return funcs;
}
var funcs = constfunc()
funcs[5]()      // 10
funcs[5]()      // 10

猜你喜欢

转载自blog.csdn.net/asdf_123123/article/details/89285300