在Node.js中实例化对象的常用方法是什么?

时间:2013-05-14 04:56:31

标签: javascript node.js

以下节点是来自Node.js测试的,我想知道为什么一种实例化对象的方法比另一种更受欢迎?

// 1
var events = require('events');
var emitter = new events.EventEmitter();
emitter.on('test', doSomething);

// 2
var net = require('net');
var server = net.createServer();
server.on('connection', doSomething);

// 3
var net = require('http');
var server = http.Server(function(req, res) {
  req.on('end', function() { ... });
});

我正在研究Node.js模块并试图找到这种API的常用方式。

2 个答案:

答案 0 :(得分:2)

#1正在使用JavaScript的new关键字来处理创建一个新对象,很可能有原型,而#2和#3正在使用工厂方法创建一些对象(可能有也可能没有原型。

// 1
function EventEmitter() {
    /* Disadvantage: Call this without `new` and the global variables 
    `on` and `_private` are created - probably not what you want. */
    this.on = function() { /* TODO: implement */ };
    this._private = 0;
}
/* Advantage: Any object created with `new EventEmitter`
   will be able to be `shared` */
EventEmitter.prototype.shared = function() {
    console.log("I am shared between all EventEmitter instances");
};

// 2 & 3
var net = {
    /* Advantage: Calling this with or without `new` will do the same thing
       (Create a new object and return it */
    createServer: function() {
        return {on: function() { /* TODO: implement */ }};
    }
};
/* Disadvantage: No shared prototype by default */

答案 1 :(得分:2)

#1和#3是相同的,http.Server可以用作工厂,因为它的第一行:

if (!(this instanceof Server)) return new Server(requestListener);

#2在顶级api函数中很有用,因为它使链接更简单:

require('http').createServer(handler).listen(8080);

而不是

(new require('http').Server(handler)).listen(8080);

核心api模块通常会公开构造函数和工厂帮助程序,例如ServercreateServer,并允许在没有new的情况下使用构造函数。