當我得到我的插座事件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);
}
}
確定'draw'實際上是叫什麼名字?這似乎不太可能。 –
最有可能是[如何在回調中訪問正確'this'/context的副本](http://stackoverflow.com/q/20279484/218196) –