简体   繁体   English

TypeScript出错了这个范围

[英]TypeScript getting wrong this scope

I am aware of this scopes but I am new to TypeScript and classes in JavaScript. 我知道this范围,但我不熟悉TypeScript和JavaScript中的类。 I am trying to access class properties within a function which is bound to a class property (to be more specific it's bound to a Socket object). 我试图访问绑定到类属性的函数中的类属性(更具体地说,它绑定到Socket对象)。

export class BrawlStarsClient {
  credentials:object
  dataBuffers:Array<Buffer>
  pingInterval:number

  constructor(credentials:object, options:object = null) {
    if (!credentials) throw new Error('No credentials have been passed to constructor')
    this.credentials = credentials

    // Setup socket
    this.client = new Socket()
    this.client.on('connect', this.onConnect)
  }

  onConnect():void {
    // In this function this refers to the socket object which is not desired
    this.dataBuffers = []
    this.pingInterval = null

    const initPacket = packetBuilder.buildLoginPacket(this.credentials)
    this.client.write(initPacket)
  }
}

In onConnect() this refers to the socket object instead of the class. onConnect()这指的是套接字对象而不是类。 What I've tried is rewriting the onConnect function to an arrow function, but that didn't help either: 我试过的是将onConnect函数重写为箭头函数,但这也无济于事:

onConnect():void { became onConnect = ():void => { onConnect():void { onConnect = ():void => {

My question: 我的问题:

How can I access my class properties inside of my onConnect() function? 如何在onConnect()函数中访问我的类属性?

You can use .bind . 你可以使用.bind .bind will carry the arguments forward to the inner function. .bind会将参数传递给内部函数。

this.client.on('connect', this.onConnect.bind(this));

or a arrow function. 或箭头功能。 You will manually have to pass arguments here. 您将手动必须在此处传递参数。

this.client.on('connect', () => this.onConnect());

Bind this in constructor : constructor绑定this

this.onConnect = this.onConnect.bind(this);

From the MDN documentation : MDN文档

The bind() method creates a new function that, when called, has its this keyword set to the provided value[.] bind()方法创建一个新函数,在调用时,将其this关键字设置为提供的值[。]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM