Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Node.js patterns of module export / require

3,076 views

Published on

2014-02-08 大阪 Node 勉強会 LT

  • If you are looking for trusted essay writing service I highly recommend ⇒⇒⇒WRITE-MY-PAPER.net ⇐⇐⇐ The service I received was great. I got an A on my final paper which really helped my grade. Knowing that I can count on them in the future has really helped relieve the stress, anxiety and workload. I recommend everyone to give them a try. You'll be glad you did.
       Reply 
    Are you sure you want to  Yes  No
    Your message goes here

Node.js patterns of module export / require

  1. 1. Node.js! patterns of module export / require 2014-02-08! Yosuke Kumakura / @kumatch
  2. 2. Yosuke Kumakura (kumatch) @kumatch Feedtailor inc. Current game: Hearthstone
  3. 3. Module code
  4. 4. module code 暗黙の宣言 var exports = module.exports = {};
  5. 5. module.exports の変更 exports = module.exports = function (foo) { // …. };
  6. 6. module.exports の変更 module.exports = 42;
  7. 7. Module patterns https://github.com/nodejs-osaka/module-patterns
  8. 8. Static methods / Constant exports.add = function (a, b) { }; ! exports.sub = function (a, b) { }; var calc = require(‘./calc’); ! var result = calc.add(10, 20);
  9. 9. Function module.exports = function (a, b) { } var add = require(‘./calc’); ! var result = add(10, 20);
  10. 10. Class constructor function Calc () { } Calc.prototype.add = function (a, b) { }; ! module.exports = Calc; var Calculator = require(‘./calc’); ! var calc = new Calculator(); var result = calc.add(10, 20);
  11. 11. Builder / Factory module.exports = function () { return { add: function (a, b) { } }; } var calcBuilder = require(‘./calc’); ! var calc = calcBuilder(); var result = calc.add(10, 20);
  12. 12. Namespaces exports.calc = { add: function (a, b) { }, sub: function (a, b) { } }; var calc = require(‘./namespace’).calc ! var result = calc.add(10, 20);
  13. 13. Singleton var caches = {}; exports.set = function (key, value) { }; exports.get = function (key) { }; var cache = require(‘./cache’); ! var item = cache.get(“item”);
  14. 14. Global declaration calc = { add: function () { } sub: function () { } } require(‘./calc’); ! var result = calc.add(10, 20);
  15. 15. Global declaration 2 var calc = { add: function () { } }; ! Object.defineProperty( Object.prototype, 'calc', { get: function() { return calc; } });
  16. 16. ※補足! ! Node モジュールの仕様上、同じモジュールで異なるバー ジョンのものを任意のコード中に利用可能なため、! モジュール側が固有名称をグローバル空間に作る仕組みは、! モジュールを読み込むバージョンとタイミング次第で、! 想定しないオブジェクトインスタンスがグローバルに割り当 てられる可能性がある。! ! 用途や理由が特別ではない限り、! モジュール側がグローバル領域にインスタンスを作り出すよ うな仕組みにしないほうがよい。

×