开发者

What happens when you declare two variables with the same name and scope in JavaScript?

What happens if I declare two variables with the same name and scope?

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

var foo = (function() {
    return {开发者_C百科
        alertMe: function() {
            alert("foo2");
        }
    }
})();

foo.alertMe();

I'm asking because I'm dynamically loading little portlets on my website and each portlet has its own script tag with a JavaScript module. The problem is, users can duplicate portlets which means there is a good chance something like the above may happen.


In your example they're both undefined anyway, so you'll have a value of undefined.

Anyway, the second var is ignored. You'll have the same result as though you didn't have it, meaning foo will be overwritten with the new value.

So, same result as if you did:

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.


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"); })(); `


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜