打字稿到javascript回调函数无法访问打字稿全局变量 [英] typescript to javascript call back function can not access typescript global variable

查看:119
本文介绍了打字稿到javascript回调函数无法访问打字稿全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过相同打字机方法传递的回调函数的JavaScript调用访问打字机全局变量。

I can not access typescript global variable from javascript call of callback function passed of same typescript method.

这是stackblitz中的示例代码。

Here is an example code in stackblitz.

https://stackblitz.com/edit/angular-quhktp

在上述incr变量示例中,该变量在组件文件中声明。当我们直接使用它时,可以通过clickthisfunction方法进行访问。但是,如果将相同的方法传递给javascript进行回调。调用回调函数,但此方法无法访问this.incr变量。

In example above incr variable which is declared in component file. Can be accessed in clickthisfunction method when we directly use it. But if the same method passed to javascript for a call back. call back function is called but this method couldn't access this.incr variable.

推荐答案

在javascript函数中, this 指向调用该函数的对象。
因此,如果您调用 this.clickthisfunction() this.incr 可以正常工作,但是如果您重新分配 this.clickthis函数到其他变量,该函数中的 this 不会是您所期望的。此 MDN页面包含有关如何 c有效。

In functions in javascript, this refers to the object on which the function was called. So if you call this.clickthisfunction(), this.incr works fine, but if you reassign this.clickthisfunction to some other variable, the this in that function won't be what you expect. This MDN page has more information about how this works.

要解决此问题,有一些选择:

To fix this, there are a few options:

绑定

您可以更改值将通过调用 .bind 来实现。
您可以在构造函数中通过添加以下行来做到这一点:

You can change what the this value in a function will be by calling .bind on it. You can do this in the constructor by adding this line:

this.clickthisfunction = this.clickthisfunction.bind(this);

您也可以在将其传递给 withargumentcallwithfunctionasargument之前绑定它。 c $ c>,
,但是绑定不是免费的,因此通常只绑定一次。

You can also bind it right before you pass it to withargumentcallwithfunctionasargument, but binding isn't free, so it's more typical to only do it once.

箭头功能

箭头函数处理的方式不同–它们从外部范围捕获而不是使用对象

Arrow functions handle this differently – they capture it from the outer scope instead of using the object the function was called on.

通过用此替换函数声明

clickthisfunction = () => {

它将从中捕获值在构造对象时。
(如果您对如何获得此值感兴趣,请看一下已转换的代码,
则有意义得多)。

it will capture the this value from when the object is constructed. (If you are interested how it's getting the this value, look at the transpiled code, it makes a lot more sense).

以上任何一个都可以解决这个不确定的问题,而您使用的大部分内容都取决于样式。唯一的区别是,第一种方法将在原型上保留功能,而第二种方法仅在实例上保留功能。不过,除非您做一些奇怪的事情,否则这可能不会有任何影响。

Either one of these should fix this being undefined, and which you use is mostly a matter of style. The only difference is that the first approach will leave a function on the prototype, while the second will only have the function on the instances. That probably won't affect anything, though, unless you do something strange.

这篇关于打字稿到javascript回调函数无法访问打字稿全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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