闭包

2017-05-08  本文已影响0人  daisx

JS变量的特殊性
(1)函数内部可以直接读取全局变量,而外部无法读取函数内部。
var n=100;
function demo() {
console.log(n);
};
demo();

(2)函数内部声明变量用var,如果不用,变量是全局变量。
function f1(){
n=100;
console.log(n);
}
var n=10;
f1();
console.log(n);
输出结果等于:100和100;调用函数f1以后,更改了全局变量。

(3)链式作用域:函数1包含函数2,函数2可以读取函数1的变量,反之则不可以。是一种描述路径的术语。

闭包:当函数a的内部函数b被函数a外的一个变量引用的时候,就创建了一个闭包。
和以下几个方面相关。
执行环境
活动对象
作用域
作用域链

闭包是一种特殊结构,可以访问函数内部的数据。

  function fu(){
        var x=10;
      return  function (a){
            x=a;
            return x;
        }
    }
var temp=fu();
    var x,y
    console.log(x = temp(1));
    console.log(y = temp(1));
    console.log(typeof x == typeof  y);
    console.log(x == y);
Paste_Image.png

变形式(立即调用函数)
写法A、(function(){})()
B、 (function(){}())

var temp=(function (){
    var x=10;
    return  function (a){
        x=a;
        return x;
    }
})();
    var x,y
    console.log(x = temp(1));
    console.log(y = temp(1));
    console.log(typeof x == typeof  y);
    console.log(x == y);

一次获取多个函数内部的值

var temp=(function (){
    var a=10;
    var b=100;
    var c=110;
    return  {
        getA: function (){
        return a;
    },
        getB:function (){
        return b;
    },
        getC:function (){
        return c;
    }}
})();
    var x, y,z;
    console.log(temp);
    console.log(x = temp.getA());
    console.log(y = temp.getB());
    console.log(z = temp.getC());

通过闭包来修改多个数据:

var temp=(function (){
    var a=10;
    var b=100;
    var c=110;
    return  {
        getA: function (){
        return a;
    },
        getB:function (){
        return b;
    },
        getC:function (){
        return c;
    },
    setA:function(value){
        if(value){a=value}
    },
    setB:function(value){
        if(value){b=value}
    },
    setC:function(value){
        if(value){c=value}
    }
    }
})();
    var x, y,z;
    console.log(temp);
    console.log(x = temp.getA()) ;
    console.log(y = temp.getB());
    console.log(z = temp.getC());
temp.setA('100');
temp.setB('200');
temp.setC('300');
    console.log(x = temp.getA()) ;
    console.log(y = temp.getB());
    console.log(z = temp.getC());

闭包的特点:(1)间接访问封闭作用域的数据。
(2)原理:函数内部声明的函数,可以访问函数内部声明的变量,如果把函数内部的函数返回,就可以间接访问函数内部的变量。
(3)延长变量的声明周期,函数内部变量释放的逻辑规则,释放时间是在任何一个地方都不再使用的时候,才会释放函数,只要外界对函数内部的任何变量还有需要引用的可能存在,都会一直被固定在内存中。继续执行。

上一篇 下一篇

猜你喜欢

热点阅读