2014-11-06 44 views
-1

只是看這個問題的範圍:What is the scope of variables in JavaScript?爲什麼值不會改變`var`的時候它是在功能

其中在根據第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 ;和最後console.log聲明此if語句不顯示控制檯中的文本。

那麼這有什麼不對?

+0

對不起,我的語法... – anni 2014-11-06 03:45:19

+1

順便說一句,這段代碼不能在嚴格模式下工作。將一個函數聲明(例如'function x(){...})'放在一個if塊內部被視爲一個函數聲明,這是不允許的。在塊之外移動函數聲明。哦,* throw *不是一個函數,所以'拋出'那裏......「;'。 – RobG 2014-11-06 04:05:19

回答

1

您在function x()的定義範圍內設置了function_code,但不會調用x()。在撥打x之前,function_call不會更改。

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()功能,因爲

相關問題