1

如果我声明两个具有相同名称和范围的变量会发生什么?

var foo = (function() {
    return {
        alertMe: function() {
            alert("foo1");
        }
    }
})();

var foo = (function() {
    return {
        alertMe: function() {
            alert("foo2");
        }
    }
})();

foo.alertMe();

我之所以这样问,是因为我在我的网站上动态加载小 portlet,每个 portlet 都有自己的带有 JavaScript 模块的脚本标记。问题是,用户可以复制 portlet,这意味着很可能会发生上述情况。

4

3 回答 3

6

在您的示例中,无论如何它们都是未定义的,因此您的值为undefined.

无论如何,第二个var被忽略了。您将获得与没有结果相同的结果,这意味着foo将被新值覆盖。

因此,结果与您所做的相同:

var foo = (function() {
    alert("foo1");
})();

foo = (function() {  // I'm overwriting the value of "foo"
    alert("foo2");
})();

EDIT: The code in the question changed. The result is now more observable if you run the code. The foo variable's reference to the first object is replaced with a reference to the second. The first reference is lost.

于 2011-01-13T03:57:39.893 回答
0

last variable will work, in your example, first var will be ignored `var foo = (function() { alert("foo1"); })();

foo = (function() { // I'm overwriting the value of "foo" alert("foo2"); })(); `

于 2011-01-13T04:08:06.057 回答
0

To avoid this problem encapsulate java scripts of different modules in different name spaces.

Name space explanation

You can also look at

How do I declare a namespace in JavaScript?

于 2011-01-13T04:27:24.727 回答