//player.js
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
module.exports = Player;
function Player(uid, emailAddress, password) {
this.uid = uid;
this.emailAddress = emailAddress;
this.password = password;
EventEmitter.call(this);
}
inherits(Player, EventEmitter);
Player.prototype = {
setUID: function(uid) {
if(uid === 'number')
this.uid = uid;
},
getUID: function() {
return this.uid;
},
setEmailAddress: function(emailAddress) {
this.emailAddress = emailAddress;
},
getEmailAddress: function() {
return this.emailAddress;
},
setPassword: function(password) {
this.password = password;
},
getPassword: function() {
return this.password;
}
}
// auth.js
var Player = require('./player');
var p = new Player(1000, '[email protected]', '12345');
// Here crashed
p.on('event', function() {
console.log('Event emitted!');
});
p.emit('event');
我是 Node.JS 编程的新手。我正在尝试了解 Node 的 EventEmitter 模块。但是,当在on(event, callback)
中调用EventEmitter 的函数时auth.js
,它会抛出该错误
TypeError: p.on is not a function
at Object.<anonymous> (/home/someone/App/libs/auth.js:7:3)
at Module._compile (module.js:571:32)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:488:32)
at tryModuleLoad (module.js:447:12)
at Function.Module._load (module.js:439:3)
at Module.runMain (module.js:605:10)
at run (bootstrap_node.js:425:7)
at startup (bootstrap_node.js:146:9)
at bootstrap_node.js:540:3
我不知道为什么会这样。我该如何解决这个问题?
您在继承后覆盖原型并释放所有继承功能:
function Player(uid, emailAddress, password) {
this.uid = uid;
this.emailAddress = emailAddress;
this.password = password;
EventEmitter.call(this);
}
inherits(Player, EventEmitter); // your prototype now contains things like, on, once, emit, ...
Player.prototype = {}; // => you overwrite your prototype and loose all methods that were on there before
因此,不要覆盖,而是将您的方法添加到现有方法中:
Player.prototype.setUID = function(uid) {
if(uid === 'number')
this.uid = uid;
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句