在调用数组的映射函数时丢失它

Losing this while calling map function of array

本文关键字:映射函数 调用 数组      更新时间:2023-09-26
Array.prototype.map.call(arr,this.parse)

对于上面的代码,我正在做的是在数组arr上应用 this.parsethis.parse中我在函数上使用了一些(例如,this.func1 (。

尽管如此,我在调用this.func1时丢失了this,似乎它指向全局对象而不是当前类。保留this的正确方法是什么?

更新正如下面的答案所建议的那样,我使用

arr.map(this.parse.bind(this))

它有效!谢谢!

您可以将this.parse绑定到当前this。请记住,this不是词法范围的,这取决于函数的调用方式。Function.bind 允许您指定this将是什么,无论它如何调用

Array.prototype.map.call(arr, this.parse.bind(this));

另一个选项是要分析的第二个可选参数,它允许您指定this。见 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Array.prototype.map.call(arr, this.parse, this);

另一种选择是使用箭头函数,这些函数确实使用词法范围的this。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

Array.prototype.map.call(arr, 
    (current, index, array) => this.parse(current, index, array));

我只是假设你正在使用打字稿,因为你用"打字稿"标记了帖子。让我们来看看你写了什么:

Array.prototype.map.call(arr,this.parse)

你为什么首先使用 call((?有什么原因吗?你写的等效于:

arr.map(this.parse)

来自 Mozilla 对 Array.map(( 函数的引用:

arr.map(callback[, thisArg](

如果为 map 提供了 thisArg 参数,则在调用时将传递给回调,以用作其 this 值。否则,将传递未定义的值以用作其此值。最终可由回调观察到的 this 值是根据确定函数看到的 this 的常规规则确定的

我认为您真正要做的是捕获当前对象的上下文。如果你只引用函数的名称,Typescript 不会这样做,因为 Javascript 不会这样做,而 Typescript 努力与现有的 Javascript 向后兼容。

我认为你想做的是这样的:

private parse(str: string): string {
    // Just an example -- parse by converting to uppercase
    return str.toUpperCase();
}
public myMethod(arr: string[]) {
    // Parse all the elements of arr
    let parsedArray = arr.map((elem) => this.parse(elem));
    // ...
}