Home  >  Article  >  Web Front-end  >  Introduction to JS closures

Introduction to JS closures

不言
不言Original
2018-07-05 17:46:061352browse

This article mainly introduces the introduction of JS closures, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

1. Scope

    var x = 0  //全局变量 x
    var y = 10 //全局变量 y
    var fun1 = function(){
        var x = 1  //fun1函数局部变量 x
        console.log(x++)
        console.log(y)
    } 
    fun1() //输出 1  10 函数内可以访问函数上级的变量
    console.log(x) //输出0 函数外部不能调用函数内部的局部变量

2. Closure

<!-- 闭包:有权访问另一个函数作用域中的变量的函数。大多是在一个函数内部创建另一个函数 -->
    var x = 0  //全局变量 x
    var fun1 = function(){
        var x = 1  //fun1函数局部变量 x
        function fun2() {
            console.log(x++) //当x = 1时 x++ = x ; ++x = x+1
        }
        return fun2  //此时fun2就是一个闭包
    } 
    var run1 = fun1()
    run1() //输出 1 
    run1() //输出 2 run1是函数是引用类型,上一步运行run1将变量x改变进而影响这步的输出

    var run2 = run1
    run2() //输出 3  因为run2 = run1 run1和run2是函数属于引用类型 所以共用一个作用域链
    run2() //输出 4

    var run3 = fun1()
    run3() //输出 1 这里不是5 run3有自己的作用域链
    run3() //输出 2

    console.log(x) //输出 0

The above is the entire content of this article. I hope it will be helpful to everyone’s learning. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

About JS Introduction to inheritance

The above is the detailed content of Introduction to JS closures. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn