为什么现代 JavaScript 文件使用如下结构:
(function () {
// some real code
}());
即我知道正在创建一个匿名函数,然后立即调用,没有传递任何参数……但是为什么要这样做而不只是调用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;
};
}());
凭借我的基本 JavaScript 和 jQuery 技能,我理解上面列出的单个命令,但我不明白为什么它们会包含在几个function
s. 我们不能打电话给:
"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));