最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Javascript: Wrapping entire script in a function call - Stack Overflow

programmeradmin0浏览0评论

I've came across a few times with this phenomena in JavaScript, where an entire script is wrapped in a function call, like this:

(function() {
    // statements...
})();

Real world example, from glow.mozilla client-side code: .js

What is this coding style used for? What's the difference between with and without the wrapped function style and when should it be used?

I've came across a few times with this phenomena in JavaScript, where an entire script is wrapped in a function call, like this:

(function() {
    // statements...
})();

Real world example, from glow.mozilla.com client-side code: https://github.com/potch/glow/blob/master/media/glow.js

What is this coding style used for? What's the difference between with and without the wrapped function style and when should it be used?

Share Improve this question asked Mar 30, 2011 at 22:33 MichaelMichael 2,9754 gold badges25 silver badges18 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

Doing it like this ensures that none of the variables/function you define go into the global scope. All scripts you include in the page share the same global scope, so if you define two variables in two separate scripts with the same name, they actually refer to the same variable.

For example, suppose you have a.js and b.js, defined like so:

// a.js
var node = document.getElementById("something");

function frob() {
   node.style.display = "none";
}

// b.js
var node = document.getElementById("something-else");

If you include b.js after a.js in your page, then when you call frob it's going to hide the "something-else" node instead of the "something" node like you would expect.

Instead, you can do something like:

// a.js
(function() {
    var node = document.getElementById("something");

    window.frob = function() {
       node.style.display = "none";
    }
})();

// b.js
(function() {
    var node = document.getElementById("something-else");
})();

And the stuff inside b.js isn't going to interfere with what's in a.js.

Note that in reality I wouldn't add functions directly onto window, instead I would do something similar to what that glow.js script you linked to has: a single global variable that represents my scripts "namespace". In jQuery, for instance, that single global variable is $ (or jQuery).

发布评论

评论列表(0)

  1. 暂无评论