这相当于
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;
}
}();
... 确保哈希/对象 shorts,* private 仅对函数 fullname*
.
所以回答你的问题,为什么不呢
function fullname(name){
var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
return shorts[name] || name;
}
这里'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(立即调用函数表达式)。这个想法是
在函数B 内创建一个函数A 并声明用于函数A 的变量
在函数 B;s 范围内,因此只有函数 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**
};
我没有看到任何其他用途。
所以这只是保持变量私有的一种方式,并且同时,
不会失去性能。
(见What is the (function() { } )() construct in JavaScript?)