当前位置:首页 > 开发 > 编程语言 > 加密解密 > 正文

[Node.js] 学习笔记 - right design for your modules

发表于: 2014-04-26   作者:cute.spring   来源:转载   浏览:
摘要: http://fredkschott.com/post/2013/12/node-js-cookbook---designing-singletons/ Private vs. Public When creating a new module, your variables and functions are kept private by default. You’ll need t
http://fredkschott.com/post/2013/12/node-js-cookbook---designing-singletons/

Private vs. Public
When creating a new module, your variables and functions are kept private by default. You’ll need to use module.exports to define your interface and make them public. This is a strait-forward process: whatever you set to module.exports becomes public, and is visible when your module is required.

Your goal when designing modules should be to keep as much code private as possible, and only export what needs to be referenced by the rest of your application. Public functions can still reference private variables and functions, so there’s no harm in being conservative when choosing between the two.

You should be able to look in one place to see exactly what’s public, what’s private, and what the hell is going on. Kill two birds with one stone: define AND export your public variables at the same time. You’ll have an explicit separation of private and public as well as a complete picture of your public interface, instead of constantly searching your code base to find which functions are being exported.
// Private
var b = 2;
function sum(x, y) {
  return x + y;
}
function isXEqualTo5() {
  return (module.exports.x == 5);
}

// Public
module.exports = {
  x: 5,
  add2: function(num) {
      return sum(b, num);
  },
  addX: function(num) {
      return sum(module.exports.x, num);
  }
}
 


Avoiding the Exports Alias
A seasoned Node veteran will know there’s a second way to export your code. exports is an alias to module.exports, which you can use instead to save yourself a few characters. But be careful: it’s just an alias. Setting individual properties works fine, but if you set the entire exports or module.exports object (as we do above) you’ll break the connection between the two and it will no longer work.

If you have the same singleton code in two different files, Node will treat these as two separate modules. If they’re completely stateless this is fine, but if you’re not careful it can cause some major headaches down the road. Make sure you keep your code in a single place so that require can cache it correctly.

[Node.js] 学习笔记 - right design for your modules

  • 0

    开心

    开心

  • 0

    板砖

    板砖

  • 0

    感动

    感动

  • 0

    有用

    有用

  • 0

    疑问

    疑问

  • 0

    难过

    难过

  • 0

    无聊

    无聊

  • 0

    震惊

    震惊

版权所有 IT知识库 CopyRight © 2009-2015 IT知识库 IT610.com , All Rights Reserved. 京ICP备09083238号