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語句是真的。
爲什麼它這樣做,我怎樣才能確保兩個腳本以相同的方式運行?
每次從不同的範圍內測試不同的'x'變量。請注意,將somescript.js中的'var x'聲明[懸掛](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting)放在頂部'if'上面的'function'。而且,你可能還沒有在這裏展示的是定義一個全局'x'。 –
@JonathanLonowski好抓。在somescript.js的'if','x'總是未定義的,因爲它的聲明被提升並且[shadows](http://en.wikipedia.org/wiki/Variable_shadowing)全局'x'。 –
[variable hoisting](http://stackoverflow.com/questions/3725546/variable-hoisting)可能有重複。還有相關的[JavaScript'hoisting'](http://stackoverflow.com/questions/15311158/javascript-hoisting) –