Home > Web Front-end > JS Tutorial > body text

Analysis of two common situations of js closure

一个新手
Release: 2017-09-22 10:24:32
Original
1142 people have browsed it

//闭包两种情况  1:函数作为返回值
function fn() {
    var max =10;
    return function bar(x) {
        if(x > max){
          console.log(x)
        }else{
            console.log(666)
        }
    }
}
var f1=fn(),max = 100;
f1(15)    //15
//这里fn()赋给f1,调用f1时,即执行bar函数,此时x=15,
//max的取值需是创建该函数的作用域内,即max=10;最后输出15.
Copy after login
//2:函数作为参数传递
    var max=10,
        fn=function (x) {
            if(x > max){
                console.log(x)
            }else{
                console.log('000')
            }
        };
        (function (f) {
            var max = 100;
            f(15)
        })(fn)
    //这是第二种情况,fn函数作为f参数,f(15)就是执行 fn(15);
    //此时x=15,max的取值应该是创建fn函数的作用域内取,即10,输出结果是15;
Copy after login

The above is the detailed content of Analysis of two common situations of js closure. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template