TypeScript出错了这个范围

时间:2017-08-21 16:45:53

标签: javascript typescript

我知道this范围,但我不熟悉TypeScript和JavaScript中的类。我试图访问绑定到类属性的函数中的类属性(更具体地说,它绑定到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)
  }
}

onConnect()中,这指的是套接字对象而不是类。我试过的是将onConnect函数重写为箭头函数,但这也无济于事:

onConnect():void {成为onConnect = ():void => {

我的问题:

如何在onConnect()函数中访问我的类属性?

2 个答案:

答案 0 :(得分:2)

您可以使用.bind.bind会将参数传递给内部函数。

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

或箭头功能。您将手动在这里传递参数。

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

答案 1 :(得分:1)

this中绑定constructor

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

来自MDN documentation

  

bind()方法创建一个新函数,在调用时,将this关键字设置为提供的值[。]