这相当于
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
function fullname(name){
return shorts[name] || name;
}
......它的作用。但
var fullname = function(){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return function(name){
return shorts[name] || name;
}
}();
... 确保 hash/objectshorts
是 *仅对函数私有fullname
的* 。
所以回答你的问题,为什么不
function fullname(name){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return shorts[name] || name;
}
Here'shorts
隐藏在里面fullname
,但正如 Dogbert 指出的那样,它更慢,因为在每次调用时都会创建shorts
散列。
但这提供了两全其美:
var fullname = function(){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return function(name){
return shorts[name] || name;
}
}();
shorts
同时保持私有,只实例化一次,因此性能也会很好。fullname
shorts
这就是他们所说的IIFE(立即调用函数表达式)。这个想法是在函数A
内部创建一个函数,并
在函数的范围内B
声明使用的变量,以便只有函数可以看到它们。A
B
A
var B = function(){
// this is B
//
val foo = {x:1}; // this is ONLY for A
val A = function(arg0) {
// do something with arg0, foo, and whatever
// and maybe return something
};
return A;
};
val A = B();
如您所见,这与
var A = (function(){
// this is in 'B'
//
val foo = {x:1}; // this is ONLY for A
return function(arg0) { // this is in A
// do something with arg0, foo, and whatever
// and maybe return something
};
})(/*calling B to get A! */);
在功能上,这与
val foo = {x:1}; // foo is visible OUTSIDE foo!
val A = function(arg0) {
// do something with arg0, foo, and whatever
// and maybe return something**strong text**
};
我没有看到任何其他用途。
所以这只是保持变量私有的一种方式,同时又不会失去性能。
(请参阅JavaScript 中的 (function() { } )() 构造是什么?)