2014-07-03 31 views
0

運行遊戲框架2.3版本,雖然它可能不相關:的Javascript:兩個if typeof運算未定義的語句給出不同的結果

我有以下內容的HTML文件:

<html> 
    <head> 
     <script type="text/javascript"> if (typeof x === 'undefined') {console.log("x not defined");} else {console.log("in html, x is %s", typeof x);} </script> 
     <script type="text/javascript" src="javascripts/somescript.js"></script> 
    </head> 
</html> 

和somescript。 js有這個:

(function() { 
    jQuery(function() { 
     if (typeof x === 'undefined') { 
      console.log("in somescript.js, x is %s", typeof x); 
      var x = something; 
      //other stuff 
     } 
    }); 
}).call(this); 

當我第一次加載頁面時,x是未定義的預期。然而,當我去同一個應用程序中的不同頁面,然後回來,在控制檯上寫着:

in html, x is object 
in somescript.js, x is undefined 

這是奇怪,因爲在HTML中,if語句是假的,但在somescript.js,相同的if語句是真的。

爲什麼它這樣做,我怎樣才能確保兩個腳本以相同的方式運行?

+0

每次從不同的範圍內測試不同的'x'變量。請注意,將somescript.js中的'var x'聲明[懸掛](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting)放在頂部'if'上面的'function'。而且,你可能還沒有在這裏展示的是定義一個全局'x'。 –

+0

@JonathanLonowski好抓。在somescript.js的'if','x'總是未定義的,因爲它的聲明被提升並且[shadows](http://en.wikipedia.org/wiki/Variable_shadowing)全局'x'。 –

+0

[variable hoisting](http://stackoverflow.com/questions/3725546/variable-hoisting)可能有重複。還有相關的[JavaScript'hoisting'](http://stackoverflow.com/questions/15311158/javascript-hoisting) –

回答

1

這是變量提升 - 如果你在函數內的任何地方聲明瞭一個變量,它的定義會被提升到最高。

x = 0; 
function y() { 
    //var x; you don't write it here, but internally this is happening 
    if (typeof x === 'undefined') { 
     alert('x is undefined'); 
     var x = 1; //because you use var, you are declaring a new variable x, 
        //so it gets hoisted to the top 
    } 
} 
y(); //alerts x is undefined 

但是,如果你這樣做:

x = 0; 
function y() { 
    if (typeof x === 'undefined') { 
     alert('x is undefined'); 
     x = 1; //we don't use var, so we aren't redeclaring it, just setting its value 
    } 
} 
y(); //nothing happens 
相關問題