title: TypeError: Cannot read property 'emit' of undefined
body: <p>The problem is that Whenever I try to fire "this.io.emit" event a TypeError occurs. It gives only while I write this statement "this.io.emit" inside "socket.on" block otherwise, if I write it outside this block it generates no error.</p>
  
  <p>This is the main server.js file to call the other libraries:</p>
  
  <pre><code>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,()=&gt; {
          console.log(`Listening`);
      });
  }}
  </code></pre>
  
  <p>my server side code is: </p>
  
  <pre><code>'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) =&gt; {
          socket.on('send message',function(data)
          {
              this.io.emit('new message',data);//here the error lies.
          });
      }); 
  }
  routesDefault()
  {
      this.routesTemplate();
      this.socketEvents();
  }}  
  module.exports = Routes;
  </code></pre>
  
  <p>I also tried to access "this.users.The length" inside socket.on the statement and it generated the same TypeError: cannot read property length. I have no idea why it is occurring. Please help me to resolve this problem.</p>
  
  <p>Client Side:</p>
  
  <pre><code>        &lt;script&gt;
          $(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+ "&lt;br/&gt;");
              });
          });
      &lt;/script&gt;
  </code></pre>