gpt4 book ai didi

javascript - 调用数组的映射函数时丢失 this

转载 作者:行者123 更新时间:2023-11-28 12:23:14 26 4
gpt4 key购买 nike

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

对于上面的代码,我正在做的是将 this.parse 应用于数组 arr,其中在 this.parse 中我使用一些关于函数的内容(例如,this.func1)。

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

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

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

并且它有效!谢谢!

最佳答案

您可以将 this.parse 绑定(bind)到当前的 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);

另一种选择是使用箭头函数,它使用词法范围的 thishttps://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));

关于javascript - 调用数组的映射函数时丢失 this,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33671713/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com