为什么myVar未定义?
问题描述:
当我得到我的插座事件drawMouse
& my draw()
功能被称为myVar
是未定义的。 为什么我无法从socket.on回调中访问this.myVar
?为什么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);
}
}
答
因为this
插座回调里面是不是指的组件。
尝试:
this.socket.on('drawMouse', (data)=>{
this.draw(data)
})
确定'draw'实际上是叫什么名字?这似乎不太可能。 –
最有可能是[如何在回调中访问正确'this'/context的副本](http://*.com/q/20279484/218196) –