Javascript:如果typeof undefined语句给出不同的结果,则为两个

时间:2014-07-03 16:59:43

标签: javascript jquery html typeof playframework-2.3

运行play framework 2.3版,虽然它可能不相关:

我有一个包含以下内容的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语句为false,但在somescript.js中,if语句为true。

为什么这样做,我怎样才能确保两个脚本以相同的方式运行?

1 个答案:

答案 0 :(得分: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