Javascript:两个 if typeof undefined 语句给出不同的结果

标签 javascript jquery html typeof playframework-2.3

运行 play 框架版本 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。

为什么要这样做,如何确保两个脚本以相同的方式运行?

最佳答案

这就是变量提升 - 如果您在函数内的任何位置声明变量,它的定义就会提升到顶部。

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

关于Javascript:两个 if typeof undefined 语句给出不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24559471/

相关文章:

html - CSS3 的逻辑与

Javascript:如何将数组元素传播到所有其他元素并制作单个数组

javascript - 无损 Backbone 集合过滤

javascript - jQuery.mouseover 从嵌套元素而不是附加监听器的元素返回事件

html - 将 SQL Server 2008 表动态转换为 HTML 表

javascript - .click 不适用于更改选项卡容器的高度

javascript - 分配一个值?

javascript - 我如何在 jquery 中使用 this 来调用元素

jquery - 使用 live() 获取加载的 iframe 内容

javascript - 如何在 webix 应用程序中读取和查看光盘文件