js closure (closure) and three cases

Take a look at his "JavaS advanced programming" is defined inside

Closure (closure) has access means to another variable function scope of the function

Found closure (closure) is a function, certain functions can be accessed through the inside of the closure variables, functions and variables that is to be accessed belongs to a closure (closure)

function fn(){				//一个闭包(closure),a被函数f访问
    var a=10;
    f();
    function f() {			
        console.log(a);			//输出10
    }
}
fn();

Here Insert Picture Description


In Chrome inside commissioning map:


Here Insert Picture Description


Example 1:


function fn(){			//一个闭包
    var a=100;			//局部变量
    
    function f() {
        console.log(a);
    }
    return f;			//返回一个函数,所以fn也是一个高阶函数
}
var ff=fn();
ff();				//这样就实现了在全局作用域下访问了局部作用域的变量

Here Insert Picture Description
The main role of closures: expanding the scope of variables

Example 2:

var uname='window';			
var object={
    uname:'object',
    funct:function () {
        return function () {		
            console.log(this);		//this指向window对象
            return this.uname;		//打印出 window字符串
    
        };
    }
};
console.log(object.funct()());		//没有闭包

Here Insert Picture Description
**

Example 3:

**

var uname='window';
var object={
    uname:'object',
    funct:function () {				//是一个闭包
        var that=this;				//this指向object对象
        return function () {
            console.log(this);			//this指向window对象
            return that.uname;			//打印出 object字符串
        }
    }
};
console.log(object.funct()());

Here Insert Picture Description

Published 24 original articles · won praise 0 · Views 249

Guess you like

Origin blog.csdn.net/weixin_45969777/article/details/104878328