当函数在函数范围内时,为什么值不会改变`var`

时间:2014-11-06 03:44:07

标签: javascript scope

只看这个问题:What is the scope of variables in JavaScript?

在接受的答案中看点3

根据他a将是4但现在看看我的功能:

function JIO_compiler(bpo){  // bpo means that " behave property object " and from here i will now start saying behave property to behave object

var bobj = bpo, // bobj = behave object
    bobj_keys =  Object.keys(bobj), // bobj_keys = behave object keys. This willl return an array 
    Jcc_keys = Object.keys(JIO_compiler_components), // Jcc = JIO compiler components
    function_code = ""; // get every thing written on every index

    if (bobj.hasOwnProperty('target') === false) { // see if there is no target defined
        console.log("No target is found"); // tell if there is no target property
        throw("there is no target set on which JIO-ASC will act"); // throw an error
    };
    if (bobj.hasOwnProperty('target') === true) {
        console.log("target has been set on "+ bobj['target']+" element"); //tell if the JIO-ASC has got target
        function x(){
            var target_ = document.getElementById(bobj['target']);
            if (target_ === null) {throw('defined target should be ID of some element');};
            function_code = "var target="+target_+";"; 
            console.log("target has successfully been translated to javascript");//tell if done
        };
    };

    for(var i = 0; i < bobj_keys.length; i++){

        if(bobj_keys[i] === "$alert"){ // find if there is  $alert on any index
            var strToDisplay = bobj[bobj_keys[i]]; 
            var _alert = JIO_compiler_components.$alert(strToDisplay);
            function_code = function_code+ _alert;
        };



    };// end of main for loop
alert(function_code);
 new Function(function_code)();
};

嗯它很大......但我的问题是在第二个if语句中。现在根据接受的答案,function_code的值应根据指示的内容而改变。但最后我警告功能代码然后它警告空白。我的意思是它应该警告至少var target = something ;以及此if语句的最后console.log语句未在控制台中显示文本。

所以这有什么问题?

2 个答案:

答案 0 :(得分:1)

您在function_code的定义中设置function x(),但永远不会调用x()。在function_call拨打电话之前,x不会发生变化。

答案 1 :(得分:1)

那是因为你的变量在函数范围内,你需要在它之外定义你的变量,如

function_code = "";
function JIO_compiler(bpo){ 
    ....

};// end of main for loop
//call the function
JIO_compiler(some_parameter);
//alert the variable
alert(function_code);

您需要先调用函数JIO_compiler(),以便将相应的值设置为function_code函数的JIO_compiler()变量,如