02.变量作用域

Posted wing

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了02.变量作用域相关的知识,希望对你有一定的参考价值。

 

 

        function sandwichMaker(magicIngredient){
            function make(filling){
                return magicIngredient +" and "+filling;
            }
            return make;
        }
        var hamAnd=sandwichMaker("ham");
        hamAnd("cheese");//"ham and cheese"
        hamAnd("mustard");//"ham and mustard"
        var turkeyAnd=sandwichMaker("turkey");
        turkeyAnd("Swiss");//"turkey and Swiss"
        turkeyAnd("Provolone");//"turkey and Provolone"

 

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

 

 

 

function f(){return "global";}
function test(x){
    function f(){return "local"}
    
    var result=[];
    if(x){
        result.push(f());
    }
    result.push(f());
    return result;
}
test(true);//["local", "local"]
test(false);//["local"]

 

function f(){return "global";}
function test(x){
    var result=[];
    if(x){
        function f(){return "local";}
        result.push(f());
    }
    result.push(f());
    return result;
}
test(true);//["local", "local"]
test(false);//f is not a function

function f(){return "global";}
function test(x){
    var g=f,result=[];
    if(x){
        g= function (){return "local";}
        result.push(g());
    }
    result.push(g());
    return result;
}
test(true);//["local", "local"]
test(false);//["global"]

 

 

var x="global";
function test(){
    var x="local";
    var f=eval;
    return f("x");
}
test();//"global"

 

以上是关于02.变量作用域的主要内容,如果未能解决你的问题,请参考以下文章

JS---闭包

Bash的变量类型

JavaScript 作用域 与 作用域链

02.变量作用域

py04_02:函数之局部变量与作用域

js程序设计02——变量作用域问题