0

当阅读一些 javascript 源代码时,我发现以下代码:

var fullname = function(){
     var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
        return function(name){
          return shorts[name] || name;
      }
 }();

返回另一个函数是更有效还是其他原因?为什么不使用:

    function fullname(name){
         var shorts = { pos: "position", w: "width", h: "height", l: "left", t: "top" };
         return shorts[name] || name; 
  }
4

2 回答 2

2

这相当于

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 同时保持私有,只实例化一次,因此性能也会很好。fullnameshorts

这就是他们所说的IIFE(立即调用函数表达式)。这个想法是在函数A内部创建一个函数,并 在函数的范围内B声明使用的变量,以便只有函数可以看到它们。ABA

 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() { } )() 构造是什么?

于 2013-01-25T08:18:59.220 回答
0

在另一个函数中返回一个函数会导致创建一个闭包。在这种情况下,内部函数将可以访问外部函数范围,其中包括 object shorts

于 2013-01-25T08:15:41.027 回答