gpt4 book ai didi

javascript - 如何自动调用数组中的函数(ecma6)

转载 作者:行者123 更新时间:2023-11-29 23:45:47 25 4
gpt4 key购买 nike

假设我有以下内容:

const a = val => val;
const b = [a];
const results = b.map(fn => fn('x'));

我很想避免在 map 中创建额外的函数,这样我就可以得到这样的结果:(我知道这样我也无法传递参数)

const results = b.map(Function.call); // This is not working

当我这样做时,Chrome 控制台显示以下错误:

VM1075:3 Uncaught TypeError: undefined is not a function

我也试过使用:

const results = b.map(Function.prototype.call);

1) 为什么它不起作用/为什么我会收到此错误消息?

2)

  • 我该如何解决?

  • 我如何修复它总是传递相同的参数? (类似于 Function.call.bind(this, 'param')

最佳答案

.map(Function.call) 将不起作用,因为当方法作为回调传递时上下文会丢失。并且上下文应该是被调用者本身。所以为了让它按预期工作(没有绑定(bind) 'x')它应该是

.map(fn => Function.call.bind(fn)())

考虑到第二个 'x' 参数应该在 第一个 fn 参数之后绑定(bind)到映射器函数,所以无法获得映射回调单独使用一系列 callbind 方法。

在 ES6 中通常的做法是

const xMapper = fn => fn('x');
...
const results = b.map(xMapper);

如果不担心可读性和可重用性,匿名 map 回调是完全没问题的。

关于javascript - 如何自动调用数组中的函数(ecma6),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44240056/

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