gpt4 book ai didi

javascript - NodeJS : Cannot call method 'push' of undefined

转载 作者:太空宇宙 更新时间:2023-11-04 03:27:07 26 4
gpt4 key购买 nike

新手尝试使用事件设置一个基本的 Nodejs 程序。我的程序似乎没问题,但我收到一条错误,提示推送函数未定义。我的印象是这是一个内置函数。有人能指出我正确的方向吗?代码如下。

//emitter.js file

function Emitter() {
this.events = {};
}


Emitter.prototype.on = function(type, listener) {
this.events = this.events[type] || [];
this.events[type].push(listener);
}


Emitter.prototype.emit = function(type) {
if (this.events[type]) {
this.events[type].forEach(function(listener) {
listener();
});
}
}


module.exports = Emitter;



// app.js file

var Emitter = require('./emitter');


var emtr = new Emitter();

emtr.on('greet', function() {
console.log('Somewhere, someone said hello');
})

emtr.on('greet', function() {
console.log('A second greeting occurred');
})


emtr.emit('greet');

最佳答案

您的 Emitter.prototype.on() 逻辑有错误。

Emitter.prototype.on = function(type, listener) {
this.events = this.events[type] || [];
this.events[type].push(listener);
}

在上面的函数中this.events = this.events[type] || []; 不正确,因为它将整个事件对象重新分配给数组。这意味着下面的行 this.events[type].push(listener) 不会是一个数组,而是 undefined

只需更正您的函数即可正确分配 this.events[type]

Emitter.prototype.on = function(type, listener) {
this.events[type] = this.events[type] || [];
this.events[type].push(listener);
}

关于javascript - NodeJS : Cannot call method 'push' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43128813/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com