繁体   English   中英

事件真正去往和形成哪些对象?

[英]To and form which objects do the events really go?

我正在尝试了解 Node.js 中的EventEmitter模块。 阅读nodejs.org 上的 apidoc告诉我:

然后可以将函数附加到对象,以便在发出事件时执行。 这些函数称为侦听器。 在侦听器函数中,this 指的是侦听器附加到的 EventEmitter。

问题是,当我稍微玩弄这个时,我发现它在我的理解中并不遵循文档。

var events = require('events');

function Person(nameInput){
    this.name = nameInput;
    this.sayMyName = function(preString){
        console.log(preString + this.name);
    }
}

Person.prototype = new events.EventEmitter();

var person1 = new Person("James");
var person2 = new Person("Daniel");

person1.addListener('sayit', function(){
    this.sayMyName("Hello ");
});

person2.addListener('sayit', function(){
    this.sayMyName("Hi ");
});

person1.emit('sayit');

//console prints out:
Hello James
Hi James

我的问题是。 鉴于文档说this refers to the EventEmitter that the listener was attached to EventEmitter(在我的情况下this refers to the EventEmitter that the listener was attached to person1 和 person2),程序的输出不应该是这样的吗?

你好詹姆斯
嗨丹尼尔

当您为所有Person实例仅初始化(恰好)一个EventEmitter时,这就是问题:

 Person.prototype = new events.EventEmitter();

这将仅创建一个在所有实例之间共享的侦听器存储 - 就像原型应该工作一样。 另请参阅在 Derived.prototype = new Base 处使用“new”关键字的原因是什么

为了使继承正确,你需要做

function Person(nameInput){
    events.EventEmitter.call(this);
    this.name = nameInput;
}

Person.prototype = Object.create(events.EventEmitter.prototype);

这不会为原型创建EventEmitter ,而只是从它继承。 然后每个Person实例将初始化它自己的发射器(即使这将由addListener完成或自动emit这仍然是一件好事)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM