2013-05-14 61 views
2

以下节点snippiest来自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

#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的情况下使用。

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 */ 
+0

为什么有人更喜欢一种方式而不是另一种方式?有什么优势? – Andy 2013-05-14 05:20:23

+0

@安迪 - 我已经标记出我的评论有优点和缺点。 – 2013-05-14 11:53:44

相关问题