为什么myVar未定义?

时间:2016-11-10 17:28:25

标签: javascript angular socket.io

当我收到套接字事件drawMouse&我的draw()函数调用myVar未定义。 为什么我无法从socket.on回调中访问this.myVar

import { Component, OnInit } from '@angular/core';

import * as io from 'socket.io-client';


@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  myVar:string;

  constructor(){
    this.socket = io("http://localhost:4300");
    this.myVar = "hello"

  }

  ngOnInit() {
      this.socket.on('drawMouse', function(data){
          this.draw(data)
      })
  }

  draw(){
    //this variable is undefined
    console.log(this.myVar);
  }
}

1 个答案:

答案 0 :(得分:3)

因为套接字回调中的 this.socket.on('drawMouse', (data)=>{ this.draw(data) }) 没有引用该组件。

尝试:

{{1}}