为什么当“var”在函数范围内时,它的值不发生变化

why value is not changing of a `var` when it is in the scope of the function

本文关键字:变化 var 范围内 函数 为什么      更新时间:2023-09-26

看看这个问题: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语句中。现在根据所接受的答案,CCD_ 2的值应当根据所指示的内容而改变。但当我最后提醒函数代码时,它会提醒空白。我的意思是,如果语句没有在控制台中显示文本,它应该至少提醒var target = something ;和最后一个console.log语句注意这一点。

那么这里面出了什么问题呢?

您在function x()的定义中设置function_code,但从未调用x()。在您呼叫x之前,function_call不会更改。

这是因为您的变量在函数范围内,您需要将它之外的变量定义为

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(),以便从JIO_compiler()函数中将适当的值设置为function_code变量,如