如何将JavaScript函数转换为在TypeScript中工作 [英] How to convert JavaScript function to work in 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屋!