簡體   English   中英

TypeScript:如何使用胖箭頭和這個?

[英]TypeScript: How to use both fat arrow and this?

我正在使用非常有用的本地胖箭頭來保留回調中的this上下文。 但是,有時我需要訪問值this ,如果我沒有使用脂肪箭頭會一直有。

一個例子是事件回調,其中this具有事件發生的元素的值(我知道在這個特定的例子中你可以使用event.currentTarget ,但我們假設你不能為了一個例子) :

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

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

注意:我遇到過這個問題 ,它解決了同樣的問題,但是在CoffeeScript中。

你可以寫一個包裝另一個函數允許訪問常用的內脂肪箭頭功能的裝飾功能, this並傳遞價值的脂肪箭頭功能作為額外的參數:

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

因此,當你使用fat-arrow函數調用thisAsThat時,這基本上會返回一個不同的回調函數,當調用它時,調用帶有所有參數的fat-arrow函數,但在前面添加this作為參數。 由於您無法綁定fat-arrow函數,因此您只需調用bind並對其進行apply ,而無需擔心丟失該值。

然后你可以像這樣使用它:

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

這將記錄this當前范圍的(按脂肪箭頭規則),在this回調函數作為that (指着事件處理程序的元素),而事件本身(但基本上,所有的參數都還在傳遞)。

您不需要為此目的使用箭頭功能。

您可以簡單地使用Function的bind來更改函數的范圍:

 function callback() { // How to access the button that was clicked? $("span").text(this.text()); } var b = $('.button'); // in Typescript you should be using let instead of var b.click(callback.bind(b)); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button class='button'>Hello, world!</button> <span></span> 


對於要在同一上下文中同時使用箭頭函數和調用其他函數的其他復雜場景,可以使用Function的call apply

// let's suppose your callback function expects a Date and a Number param
$('.button').click(() => callback.call(this, new Date(), 23));
// or
$('.button').click(() => callback.apply(this, [new Date(), 23]));

@ poke的答案是正確的想法,但有幾個問題:

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

首先, arguments不是一個真正的數組,所以如上所示調用concat()將導致嵌套數組:

[0] = this
[1] = [ [0] = param1, [1] = param2, ... ]

要解決此問題,請使用slice()arguments轉換為true數組:

        return callback.apply(null, [this].concat(Array.prototype.slice.call(arguments)));

結果:

[0] = this
[1] = param1
[2] = param2
...

其次,將第一個參數傳遞給apply()的null對我來說不起作用; 我必須通過類Foo的this明確。 這是一個完整的例子:

class Foo {

    public setClickHandler(checkbox: JQuery): void {
        checkbox.click(this.captureThis(this.onCheckboxClick));
    }

    protected onCheckboxClick(checkbox: HTMLInputElement, event: Event) {
        // 'this' refers to class Foo
    }

    protected captureThis(callback) {
        var self = this;
        return function () {
            return callback.apply(self, [this].concat(Array.prototype.slice.call(arguments)));
        }
    }

}

使用這種方法, onCheckboxClick()回調可以訪問類this和checkbox元素(作為第一個參數), this在典型的click事件回調中就是這樣。 使用captureThis()的缺點是你丟失了TypeScript的回調類型安全性,因此Typescript無法阻止你弄亂回調函數簽名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM