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"

原文地址:https://www.cnblogs.com/wingzw/p/7486289.html