TypeScript:如何同时使用粗箭头和该箭头? [英] TypeScript: How to use both fat arrow and this?

查看:69
本文介绍了TypeScript:如何同时使用粗箭头和该箭头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用非常有用的本地胖箭头在回调中保留 this 上下文.但是,有时我需要访问 this 的值,如果我没有使用粗箭头的话.

I'm using the extremely useful local fat arrow to preserve this context in callbacks. However, sometimes I need to access the value that this would've had if I hadn't used the fat arrow.

一个示例是事件回调,其中 this 具有事件发生所在元素的值(我知道在此特定示例中,您可以使用 event.currentTarget ,但为了示例,假设您不能这样做):

One example are event callbacks, where this has the value of the element that the event happened on (I'm aware that in this particular example you could use event.currentTarget, but lets assume you can't for the sake of an example):

function callback() {
    // How to access the button that was clicked?
}

$('.button').click(() => { callback() });

注意::我遇到过

Note: I've come across this question which deals with this exact same issue, but in CoffeeScript.

推荐答案

您可以编写一个装饰器函数,该函数将胖箭头函数包装在另一个函数中,该函数允许访问通常的 this 并传递该值作为胖箭头函数的附加参数:

You could write a decorator function that wraps a fat-arrow function inside another function which allows the access to the usual this and passes that value to the fat-arrow function as an additional argument:

function thisAsThat (callback) {
    return function () {
        return callback.apply(null, [this].concat(arguments));
    }
}

因此,当您使用fat-arrow函数调用 thisAsThat 时,这基本上会返回一个不同的回调函数,该回调函数在调用时将调用所有参数的fat-arrow函数,但会添加 this作为前面的参数.由于无法绑定粗箭头函数,因此可以在其上调用 bind apply ,而不必担心丢失值.

So when you call thisAsThat with a fat-arrow function, this basically returns a different callback function that, when called, calls the fat-arrow function with all the arguments but adds this as an argument in the front. Since you cannot bind fat-arrow functions, you can just call bind and apply on it without having to worry about losing the value.

然后您可以像这样使用它:

You can then use it like this:

element.addEventListener('click', thisAsThat((that, evt) => console.log(this, that, evt)));

这将记录当前作用域的 this (按照胖箭头规则),回调函数的 this 记录为 that (指向事件处理程序的元素)和事件本身(但基本上所有参数仍会传递).

This will log the this of the current scope (as per fat-arrow rules), the this of the callback function as that (pointing to the element for event handlers), and the event itself (but basically, all arguments are still passed on).

这篇关于TypeScript:如何同时使用粗箭头和该箭头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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