闭包和变量提升


关于闭包的3要点

1 js允许引用函数外部的变量
2 函数能够引用外部函数,即使函数已经返回,一个函数能够引用任何作用域内的变量,包括参数和函数外部的变量

function sandwichMaker(ingredient) {
    return function(filling) {
        console.log(ingredient + " and " + filling);
    };
}
var make = sandwichMaker("apple");
make("butter"); // "appele and butter"
// 内部返回的匿名函数可以访问sandwichMaker中参数,即使sandwichMaker已经return了
// javascript中function是firs-class citizen, 意味着函数可以作为参数或者返回值

3 闭包能够更新外部变量的值,实际上闭包是通过引用的方式来与外部变量建立联系,而不是拷贝外部变量的值

function box() {
    var val = undefined;
    return {
        get: function() { return val; },
        set: function(newVal) { val = newVal;},
        type: function() { typeof val; }
    };
}
var b = box();
b.type(); // undefined
b.set("hello");
b.get(); // "hello"
b.type(); // "string"

变量提升(Hoisting)

ES5之前,javascript是没有块级作用域的,所有的变量都是通过var 来声明,ES6引入let 关键字,并引入块级作用域的概念.

1.隐式提升变量声明位置,在var声明处赋值

function f() {                            function f() {
    // ...                                     var x;  // 提升到此处声明
   // ...                                      // ...
    {                                       {
        var x = 15;     =>实际上                x = 15 // 此处赋值
        // ....                                // ...
    }                                      }
}                                         }

使用函数表达式时注意,只有变量提升

hello();
function hello() { // 函数statement
  console.log('hello')
}

great();

var great = function() { // 函数表达式
  console.log('great')
}

// 运行结果
‘hello’
Reference Error

报错的原因在于, var great 中 只有变量 'great' 提升,而匿名函数并没有提升

let块级作用域, 变量不再隐式提升


常见陷阱

function wrapElements(a) {
    var result = [];
    for (var i = 0, n < a.length; i < n; i++) {
        resule[i] = function() { return a[i]; };
    }
    return result;
}

var wrapped = wrapElements([10, 20, 30]);
wrapped[0](); // ?

看起来没什么问题,应该返回10, 但是实际上返回undefined,函数wrapElements绑定3个局部变量i, n, result,在调用wrapElements函数时在内存中为每一个变量分配一个"槽点"(slot)用来存储变量所赋的值,每次循环时,内部匿名函数形成一个闭包,引用i,我们期望的是 i 的值每次循环匿名函数都能够存储 i 的值,实际上i是引用值,每次循环之后都会改变,内部函数最终存储的是i最后的值,关键点在于: Closure store their outer variables by reference, not by value.
更改方法:

// 1.使用IIEF模拟块级作用域,立即执行每一次内部函数的调用
function wrapElements(a) {
    var result = [];
    for (var i = 0, n < a.length; i < n; i++) {
        (function(j) {
             resule[i] = function() { return a[j]; };
        })(i)
       
    }
    return result;
}

// 2.使用ES6 let 关键词创建块级作用域
function wrapElements(a) {
    var result = [];
    for (let i = 0, n < a.length; i < n; i++) {
        resule[i] = function() { return a[i]; };
    }
    return result;
}

你可能感兴趣的:(闭包和变量提升)