为什么要使用(function(){....}());

Ale*_*ber 10 javascript

可能重复:
(function(){})()构造如何工作以及人们为什么使用它?

为什么现代JavaScript文件使用如下构造:

(function () {
   // some real code
 }());
Run Code Online (Sandbox Code Playgroud)

即我理解正在创建一个匿名函数,然后立即调用,没有传递任何参数......但为什么这样做而不只是调用some real code?什么是外部圆形支架?

特别是我正盯着Github 上的文件js/start.js:

(function() {
    "use strict";

    wooga.castle.GRID_UNIT = 48;
    wooga.castle.IMAGES_BASE_URL = "images/entities/";

    (function () {
        var style = document.createElement('div').style,
            prefix;
        var candidates = {
            webkit: 'webkitTransform',
            moz:    'MozTransform', // 'M' is uppercased
            ms:     'msTransform',
            o:      'oTransform',
            '':     'transform'
        };
        for (var prefix in candidates) {
            var candidate = candidates[prefix];
            if ('undefined' !== typeof style[candidate]) {
                wooga.castle.prefix = prefix;
                wooga.castle.prefixedTransform = candidate;
                break;
            }
        }
    }());

    // XXX why the 2 wrapped "function"s here? XXX

    wooga.castle.isNativeWrapper = function() {
        var result = !wooga.castle.capabilities.desktop && !wooga.castle.capabilities.android && (! /Safari/.test(navigator.userAgent));
        wooga.castle.isNativeWrapper = function () {
            return result;
        };
        return result;
    };
}());
Run Code Online (Sandbox Code Playgroud)

凭借我的基本JavaScript和jQuery技能,我理解上面列出的单个命令,但我不明白为什么它们包含在几个functions中.我们不能打电话:

    "use strict";

    wooga.castle.GRID_UNIT = 48;
    wooga.castle.IMAGES_BASE_URL = "images/entities/";
    var style = document.createElement('div').style,
        prefix;
    var candidates = {
        webkit: 'webkitTransform',
        moz:    'MozTransform', // 'M' is uppercased
        ms:     'msTransform',
        o:      'oTransform',
        '':     'transform'
    };
    for (var prefix in candidates) {
        var candidate = candidates[prefix];
        if ('undefined' !== typeof style[candidate]) {
            wooga.castle.prefix = prefix;
            wooga.castle.prefixedTransform = candidate;
            break;
        }
    }

    wooga.castle.isNativeWrapper = !wooga.castle.capabilities.desktop && !wooga.castle.capabilities.android && (! /Safari/.test(navigator.userAgent));
Run Code Online (Sandbox Code Playgroud)

Roc*_*mat 10

这样做是为了使内部代码不会干扰全局范围中的变量.

例如:

var myLibrary = {};
var _privateVar = [];
Run Code Online (Sandbox Code Playgroud)

现在,这两者都是全球性的.但是,我不希望这样.所以,如果我创建一个函数,我可以创建一个新的范围.

(function(){
    window.myLibrary = {}; // global
    var _privateVar = []; // private
}());
Run Code Online (Sandbox Code Playgroud)

  • @AlexanderFarber:外括号是因为`function(){}()`是语法错误.外括号将其转换为表达式. (4认同)
  • 好的,谢谢,为什么你的代码需要外圆括号`(.....);`? (2认同)
  • @AlexanderFarber:我不知道.这似乎是多余的. (2认同)