【问题标题】:Javascript: two if typeof undefined statements giving different resultsJavascript:两个 if typeof undefined 语句给出不同的结果
【发布时间】:2014-07-03 16:59:42
【问题描述】:

运行 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。

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

【问题讨论】:

  • 每个都在不同的范围内测试不同的x 变量。请注意,somescript.js 中var x 的声明是hoistedfunction 的顶部,在if 的上方。而且,您可能在此处未显示的其他内容正在定义全局 x
  • @JonathanLonowski 很好。在 somescript.js 的 if 处,x 始终未定义,因为它的声明被提升,shadows 全局 x
  • variable hoisting 的可能重复项。也相关JavaScript 'hoisting'

标签: javascript jquery html typeof playframework-2.3


【解决方案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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2020-08-13
    • 1970-01-01
    • 1970-01-01
    • 2018-10-15
    相关资源
    最近更新 更多