最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What's the benefit to export functions with self invoke functions than direct return - Stack Overflow

programmeradmin2浏览0评论

I've checked a lot of codes and I've saw a lot of people doing

module.exports = (function(){
  return {
    functionA: function() {

      }
    },
    functionB: function() {

    }
  };
})();

so, why not just do

module.exports = {
  functionA: function() {

  },
  functionB: function() {

  }
};

Thanks!

I've checked a lot of codes and I've saw a lot of people doing

module.exports = (function(){
  return {
    functionA: function() {

      }
    },
    functionB: function() {

    }
  };
})();

so, why not just do

module.exports = {
  functionA: function() {

  },
  functionB: function() {

  }
};

Thanks!

Share Improve this question edited Jul 10, 2015 at 21:34 Pointy 414k62 gold badges594 silver badges627 bronze badges asked Jul 10, 2015 at 21:34 John DoeJohn Doe 531 silver badge3 bronze badges 1
  • Self invoke functions keep scope/context of inner functions in the first example. See stackoverflow./questions/19850234/… for more info about Node.js modules. – adamkonrad Commented Jul 10, 2015 at 22:18
Add a ment  | 

3 Answers 3

Reset to default 5

Your first example allows you to hide variables within its own closure scope that can be shared with your return object's methods. The For example, if you did the following...

var foo = (function(){
   var x = 2;
      return {
        addToTwo: function(y){
        return x + y;
      },
      subtractFromTwo: function(y){
        return x - y;
      }
   }
};

The above example shows that the x variable is protected and shared between addToTwo and subtractFromTwo. The second example only will allow you to make x as part of the object without the same protection.

module.exports = {
  x: 3,
  functionA: function() {
     return this.x;
  },

};

x can be altered in this example.

Those are exactly the same. It's a stylistic decision.

According to the Node.js docs:

Variables local to the module will be private, as though the module was wrapped in a function.

You could also do it this way:

module.exports.functionA = function() {

};

module.exports.functionB = function() {

};

Or:

// either method for creating a function works
function functionA () {}

var functionB = function () {} 

module.exports = {
    functionA : functionA,
    functionB : functionB
};

One of the greatest advantages of directly invoked functions is the use of closures which cannot be obtianed in a separate manner, so literally they are not the same.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论