NodeJS: module.exports
Blogs20122012-06-15
JavaScript Classes, Prototypes, and Closures
Here is a helpful video regarding on NodeJS - how to write the JS codes:
http://nodetuts.com/tutorials/28-javascript-classes-prototypes-and-closures.html#video.
I collected the sample codes and list here for quick retrieving:
var Adder = function(a, b) {
this.a = a;
this.b = b;
};
Adder.prototype.add = function() {
return this.a + this.b;
};
module.exports = Adder;
--> node
> Var Adder = require('./adder');
> Adder [Function]
> var adder = new Adder(1,2);
> adder {object}
> adder.__proto__ { add: [Function] }
---------- 2. Add default --------
var Adder = function(a, b) {
this.a = a;
this.b = b;
};
Adder.prototype.coalesce = function() {
if(! this.a) { this.a = 0; }
if(! this.b) { this.b = 0; }
};
Adder.prototype.add = funciton() {
this.coalesce();
return this.a + this.b;
}
module.exports = Adder;
--> node
> var Adder = require('./adder');
> var adder = new Adder(1);
> adder.add()
> adder.__proto__.coalesce = funciton() {}
> adder.add()
> adder.a
------ 3. Avoid expose: closure -----
var Adder = function(a, b) {
function coalesce() {
if(! a) { a = 0; }
if(! b) { b = 0; }
};
this.add = function() {
coalesce();
return a + b;
}
};
module.exports = Adder;
--> node
> var Adder= require('./adder');
> var adder = new Adder(1,2);
> adder
> adder.add();
----- 4. Remove new: return {} ------
var Adder = function(a, b) {
function coalesce() {
if(! a) { a = 0; }
if(! b) { b = 0; }
};
function add() {
coalesce();
return a + b;
}
return {
add: add
};
};
module.exports = Adder;
--> node
> var Adder= require('./adder');
> var adder = Adder(1,2);
> adder.__proto__
> adder.add()
----- 5. working with Node's modules as an event emitter ------
var EventEmitter = require('events').EventEmitter;
var Adder = function(a, b) {
var that;
function coalesce() {
if(! a) { a = 0; }
if(! b) { b = 0; }
};
function add() {
coalesce();
that.emit('add', a, b);
return a + b;
}
that {
add: add
};
that.__proto__ = EventEmitter.prototype;
return that;
};
-->node
> var Adder = require('./adder');
> var adder = Adder(1,2)
> adder.on('add', function(a,b) {
console.log('ADDING', a, 'and', b);
});
> adder.add();