Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/401.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么myVar没有定义?_Javascript_Angular_Socket.io - Fatal编程技术网

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)
      })