【问题标题】:difference between var someVariable in Global scope and window["someVariable"] in JavaScript [duplicate]全局范围内的 var someVariable 和 JavaScript 中的 window["someVariable"] 之间的区别 [重复]
【发布时间】:2012-06-07 20:46:04
【问题描述】:

可能重复:
Javascript global variables
Should I use window.variable or var?

问题:定义全局变量的两种方式:

  1. var someVariable 在全球范围内;
  2. window["someVariable"] = “some value”;有什么区别?

在我的测试中,两种方式在 IE 中有所不同(从 IE6 到 IE8)。 (IE9还可以) 您可以在我的博客中查看:ie-naming3.html,或者运行以下代码:

<!doctype html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Test naming in IE6</title>
    <style type="text/css">

    </style>
    <script type="text/javascript">

            window.foo = window.foo || {};
            foo.eat = function(){
                alert("ie6");
            };

    </script>
</head>
<body>
    <div id="container">

    </div>
    <script type="text/javascript">
        alert(typeof window.foo.eat);
    </script>
    <!--   <script type="text/javascript" src="./ie6-naming.js"></script> -->
    <script>
//        alert(typeof window.foo.eat);
var foo = foo || {};      
        alert(typeof foo.eat);
    </script>
</body>
</html>

感谢任何想法!

编辑:

问题是:运行代码,你得到两个警报:第一个显示你“函数”,但第二个显示你“未定义”,为什么?

【问题讨论】:

  • 您的网站无法加载,因此您应该使用 jsfiddle。这里真正的问题/问题是什么?
  • @epascarello 抱歉,我不知道链接无法加载。我的意思是:代码的结果是:函数(来自第一个警报)未定义(来自第二个警报)。 foo 的后一个声明覆盖了前者。为什么?

标签: javascript namespaces global


【解决方案1】:

在全局范围内没有区别,在闭包或函数中会有所不同:

(function() {
    var a = 1;
})();
alert(a); //doesn't work

(function() {
    window.a = 1; // or a = 1; (w/o the var) but not recommended (see comments)
})();
alert(a); //works!!

【讨论】:

猜你喜欢
  • 2021-06-22
  • 2017-08-18
  • 2016-09-04
  • 2018-03-13
  • 1970-01-01
  • 2021-03-28
相关资源
最近更新 更多