簡體   English   中英

Angular 6+ 如何將內部函數與類變量一起使用?

[英]Angular 6+ How to use inner functions with class variables?

我想在處理 5 個不同的用戶輸入數組時使用 array.filter(my_func()) 優雅地返回沒有用戶剛剛刪除的元素的數組,並帶有一個私有的 filterInput 類變量。 但是, my_func() 在用作內部調用時沒有“this”上下文。

有一個更好的方法嗎? 寧願不在 5 個不同的調用者中編寫相同的過濾器函數,只是為了保持范圍。

MyClass
    private inputArray1: string[];
...
    private filterInput: string;
...
    private filterFunc(element, index, array) {
        return (element !== this.filterInput);
    }
...
    public caller1(input: string) {//this is called from the onclick() in the HTML
        this.filterInput = input;
        this.inputArray1 = this.inputArray1.filter(this.filterFunc());
    }

任何人都知道如何在不廢棄過濾器實用程序的情況下完成此操作,只需使用搜索編寫我自己的然后返回 slice1 + slice2?

您可以使用函數綁定方法來修復this引用

public caller1(input: string) {
  this.filterInput = input;
  this.inputArray1 = this.inputArray1.filter(this.filterFunc.bind(this));
}

或者你可以使用javascript箭頭函數

public caller1(input: string) {
  this.filterInput = input;
  this.inputArray1 = this.inputArray1.filter((elm,idx,arr) => this.filterFunc(elm,idx,arr));
}

另一種方式是 javascript 函數閉包🧙‍♂️

private filterFunc() {
    const filterInput = this.filterInput;
    return function (element, index, array) {
         return (element !== filterInput);
}

public caller1(input: string) {
    this.inputArray1 = this.inputArray1.filter(this.filterFunc());
}

但我更喜歡使用這樣的參數來設置過濾器值

private filterFunc(filterInput) {
    return function (element, index, array) {
         return (element !== filterInput);
}

public caller1(input: string) {
    this.inputArray1 = this.inputArray1.filter(this.filterFunc(this.filterInput));
}

閉館🚀🚀

有關如何解決此問題的一般解決方案,請參閱如何在回調中訪問正確的“ this ”? ,但對於filter方法,只需將上下文作為第二個參數傳遞:

this.inputArray1 = this.inputArray1.filter(this.filterFunc, this);
//                                                          ^^^^

雖然這是相對單調的。 您根本不會使filterFunc成為實例方法,您只需在caller1方法中定義一個本地函數並使其成為input參數閉包

public caller1(input: string) {
    function filterFunc(element, index, array) {
        return (element !== input);
//                          ^^^^^
    }
    this.inputArray1 = this.inputArray1.filter(filterFunc);
//                                             ^^^^^^^^^^
}

或者做同樣的事情,但通過將函數內聯定義為表達式、使用箭頭語法並省略不需要的參數來更簡潔:

public caller1(input: string) {
    this.inputArray1 = this.inputArray1.filter(element => element !== input);
}

另一種可能的方法是像這樣編寫“filterFunc”(ts 編譯器不會將它放在原型上):

private filterFunc = (element, index, array) => {
    return (element !== this.filterInput);
}

並像這樣使用它:

this.inputArray1 = this.inputArray1.filter(this.filterFunc);

暫無
暫無

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

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