CNode

关于引入EventEmitter对象的方法的方式

Hhopehack发布于13 年前最后回复13 年前8 回复6831 浏览0 收藏

构造函数中使用如下代码:

events.EventEmitter.call(this);

另外的方式:

util.inherits(appDAO, events.EventEmitter);

这两种方式是否重复?

原始代码如下:

function appDAO(config){
    if(config){
        db_option = config;
    }
    else{
        db_option = new db_config();
    }
    events.EventEmitter.call(this);
    logger.debug(db_option);
    pool = mysql.createPool(db_option);
    //设置mysql连接池单次最大连接数,默认10
    //pool.connectionLimit(10);
    //设置连接池最大请求队列长度,默认0,即不限制.如果设置了则超过长度时getConnection会返回错误
    //pool.queueLimit(0);
    logger.info('init mysql pool');
}
//继承events模块,用于处理消息
util.inherits(appDAO, events.EventEmitter);

外部引用appDAO来调用EventEmitter的方法。

我觉得这其中一个语句是没有必要的,不知道我理解的对不对

查看回复

回复 (8)

B
brighthas#1·13 年前

Example:

function O(){
  EventEmitter.call(this);
  
}

util.inherits(O,EventEmitter);

all should use.


签名: 交流群244728015 《Node.js 服务器框架开发实战》 http://url.cn/Pn07N3

B
brighthas#3·13 年前
引用 brighthasExample: all should use. 签名: 交流群244728015 《Node.js 服务器框架开发实战》 http://url.cn/Pn07N3

@hopehack

no, must all.


签名: 交流群244728015 《Node.js 服务器框架开发实战》 http://url.cn/Pn07N3

J
jiyinyiyong#4·13 年前

是有点怪, 不过看源码还是能理解.. .call 只是绑定方法, 而 .inherents.prototype 指向父类:

coffee> console.log util.inherits.toString()
function (ctor, superCtor) {
  ctor.super_ = superCtor;
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  });
}
H
hopehack#5·13 年前
J
jiyinyiyong#6·13 年前
引用 jiyinyiyong是有点怪, 不过看源码还是能理解.. .call 只是绑定方法, 而 .inherents 将 .prototype 指向父类:

@hopehack 很可能不够的.. 一般的比我创建一个类, 可能是这样写:

Cat = function(name) {
  this.name = name
}
kitty = new Cat('kitty')

其中 new 的作用, 一个是处理原型链, 一个是初始化变量 this.name 对照上边的 .inherits 的代码, 只是绑了原型链, 没有初始化变量.. 而 .call 的调用就是做了这一步, 往 this 上写数据. 那么在一般的场景里, 很多都有初始化变量的步骤, 那一句就不够了

X
XadillaX#7·13 年前

-. - 我都是inherits继承的

B
brighthas#8·13 年前
引用 XadillaX. 我都是inherits继承的

also correct, but best both. because need instanceof sometimes.

EventEmitter new version is corrent, old version must both.


签名: 交流群244728015 《Node.js 服务器框架开发实战》 http://url.cn/Pn07N3

参与回复
登录后即可参与回复。登录