Javascript 为什么myVar没有定义?
当我获取套接字事件时,Javascript 为什么myVar没有定义?,javascript,angular,socket.io,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', st
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);
}
}
因为套接字回调中的
这个没有引用组件
尝试:
您确定实际调用了draw
?这似乎不太可能。很可能是@FelixKling的复制品哦,我没有意识到这一点,怎么会这样呢没有想法;)也许我误解了文本。@echonax有效。我想这是因为尝试使用es6范围,但没有使用新的函数语法,对吗?@JustinYoung。我们有点困惑,您是否真的成功调用了该方法。@echonax是的,它正在调用该方法,但当我注销方法调用中的myVar值时,它没有定义。我猜这只是越界了。谢谢你的帮助!
this.socket.on('drawMouse', (data)=>{
this.draw(data)
})