当我收到我的套接字事件 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);
}
}
最佳答案
因为套接字回调中的 this
没有引用组件。
尝试:
this.socket.on('drawMouse', (data)=>{
this.draw(data)
})
关于javascript - 为什么 myVar 未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40533654/