TypeError:无法读取未定义的属性“emit”

问题是,每当我尝试着触发“this.io.emit”事件发生TypeError。 只有当我在“socket.on”块中写这个语句“this.io.emit”时才给出,否则,如果我把它写在这个块之外,它就不会产生错误。

这是调用其他库的主要server.js文件:

const express = require('express'), http = require('http'), socketio = require('socket.io'); class App{ constructor() { this.port = process.env.PORT || 81; this.host = `localhost`; this.app = express(); this.http = http.Server(this.app); this.socket = socketio(this.http); } appConfig(){ new config(this.app); } appRoutes(){ new routes(this.app,this.socket).routesDefault(); } appDefault(){ this.appConfig(); this.appRoutes(); this.http.listen(this.port,this.host,()=> { console.log(`Listening`); }); }} 

我的服务器端代码是:

 'use strict'; class Routes { constructor(app,socket) { this.app = app; this.io = socket; this.users=[]; } routesTemplate() { this.app.get('/',function(req,res){ res.render('index'); }); } socketEvents() { this.io.on('connection',(socket) => { socket.on('send message',function(data) { this.io.emit('new message',data);//here the error lies. }); }); } routesDefault() { this.routesTemplate(); this.socketEvents(); }} module.exports = Routes; 

我也尝试访问socket.on中的“this.users.The length”,它产生了相同的TypeError:无法读取属性的长度。 我不知道为什么发生。 请帮我解决这个问题。

客户端:

  <script> $(function($){ var socket = io.connect(); var $messageForm = $('#send-message'); var $messageBox = $('#message'); var $chat = $('#chat'); $messageForm.submit(function(e){ e.preventDefault(); socket.emit('send message',$messageBox.val()); $messageBox.val(""); }); socket.on('new message',function(data){ $chat.append(data+ "<br/>"); }); }); </script> 

this是你的代码中的一个问题。 要通过当前上下文使用bindArrow函数。 在JavaScript中,这个值是由你如何调用函数定义的,在你的情况下是socket对象。

 socketEvents() { this.io.on('connection',(socket) => { socket.on('send message',function(data) { this.io.emit('new message',data);//here the error lies. }bind(this)); }); } 

PS:编辑,现在这个代码工作正常。 我想build议下面的文章描述它。

ES6的箭头函数和Function.prototype.bind绑定的函数有什么区别(如果有的话)?

这是因为这个内部函数的上下文是不同的。

尝试:

 socketEvents() { this.io.on('connection',(socket) => { socket.on('send message',function(data) { socket.emit('new message',data);//here the error lies. }); }); }