如何将JavaScript函数转换为在TypeScript中工作 [英] How to convert JavaScript function to work in typescript

查看:80
本文介绍了如何将JavaScript函数转换为在TypeScript中工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我这样写,就不能使用this关键字

If I write it like this, I can't use this keyword

  LoadDrawing(drawing_name) {
    this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name);
  }


  LoadCB(drawing, drawing_name) {
    if (drawing == null) {
     return;
    }   
    this.DrawingName = drawing_name;
    drawing.SetParentElement("glg_area");
  }

我不知道要传递什么,使用参数传递时drawing & drawing_name会得到相同的结果

I dont know what to pass that drawing & drawing_name get same thing when pass using params

LoadDrawing(drawing_name) {
        this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB(param1,param2),drawing_name);
      }

推荐答案

您可以通过将LoadCB的this绑定定义为箭头函数来保留它:

You can preserve the this binding of LoadCB by defining it as an arrow function:

LoadDrawing(drawing_name) {
    this.glg.LoadWidgetFromURL(drawing_name, null, this.LoadCB,drawing_name);
}


LoadCB = (drawing, drawing_name) => {
    if (drawing == null) {
     return;
    }   
    this.DrawingName = drawing_name;
    drawing.SetParentElement("glg_area");
}

请注意,这与TypeScript无关,但与ES6 JavaScript类无关.

ES6类方法以与使用function关键字定义的函数相同的方式对待this绑定-依赖于调用位置而不是函数的词法范围.箭头函数使用词法作用域,因此在上述情况下会保留this绑定.

ES6 class methods treat this bindings in the same way as a function defined using the function keyword does - in a way that is dependent on the call site rather than the lexical scope of the function. Arrow functions use lexical scope and so preserve the this binding in situations such as the above.

这篇关于如何将JavaScript函数转换为在TypeScript中工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆