Function.call方法作为回调 [英] Function.call method as callback

查看:101
本文介绍了Function.call方法作为回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,如果我错过了一些东西,但当我尝试使用call方法作为回调时,它会在Chrome和Node.js中给出奇怪的错误。

Excuse me if I've something missed, but when I try to use call method as a callback it gives me strange error in both Chrome and Node.js.

['  foo', ' bar  '].map(String.prototype.trim.call);
TypeError: ["  foo", " bar  "].map is not a function
at Array.map (native)

但这些片段有效:

['  foo', ' bar  '].map(function (item) { 
    return String.prototype.trim.call(item);
}); // => ['foo', 'bar']
/*
  and ES2015
*/
['  foo', ' bar  '].map(function () { 
    return String.prototype.trim.call(...arguments);
}); // => ['foo', 'bar']

此外我还检查了 call function:

Also I've checked type of call function:

typeof String.prototype.trim.call; // => 'function'

我做错了什么?谁能解释一下为什么我会收到这样的错误?谢谢。

Am I doing something wrong? Could anyone please explain me why I get such error? Thanks.

推荐答案

解决问题的最简单方法就是写出来:

The easiest solution to your problem is to just write it out:

['  foo', ' bar  '].map(s => s.trim());

如果你想传递一个函数,你需要一些比你想要的更复杂的东西,沿着这条线of

If you want to pass a function, you will need something more complicated than you want, along the lines of

.map(Function.call.bind(String.prototype.trim))

或者如果您愿意

.map(Function.call, String.prototype.trim)

此问题可能会回答您的所有问题。

This question may answer all your issues.

这篇关于Function.call方法作为回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆