为什么不[[A“,”B“,”C“]。map(String.prototype.toLowerCase.call)有效? [英] Why doesn't ["A","B","C"].map(String.prototype.toLowerCase.call) work?

查看:56
本文介绍了为什么不[[A“,”B“,”C“]。map(String.prototype.toLowerCase.call)有效?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这当然会返回您的期望:

This, of course, returns what you would expect:

["A","B","C"].map(function (x) {
    return x.toLowerCase();
});
// --> ["a", "b", "c"]

使用String.prototype.toLowerCase也是如此.call:

So does using String.prototype.toLowerCase.call:

["A","B","C"].map(function (x) {
    return String.prototype.toLowerCase.call(x);
});
// --> ["a", "b", "c"]

如果您通过额外的map给出的参数,因为它抛弃了参数:

It also works if you pass the extra arguments given by map, as it throws away the arguments:

["A","B","C"].map(function (x, index, arr) {
    return String.prototype.toLowerCase.call(x, index, arr);
});
// --> ["a", "b", "c"]

但是,这不起作用:

["A","B","C"].map(String.prototype.toLowerCase.call);
// --> TypeError: undefined is not a function

以下也不起作用,因为 arguments 具有Object原型而不是Array原型,因此 slice 未定义。上述行为的原因可能是因为这样的事情 - 其中 slice 还是内部使用了一些其他类似的Array函数?

The following doesn't work either, because arguments has the Object prototype instead of the Array prototype, so slice is undefined on it. Is the reason for the above behavior perhaps because of something like this-- where slice or some other similar Array function is used internally?

["A","B","C"].map(function (x) {
    return String.prototype.toLowerCase.apply(x, arguments.slice(1));
});
// --> TypeError: undefined is not a function


推荐答案

这是一个特殊的JavaScript的点符号的行为。

This is a special behavior of JavaScript's dot-notation.

toLowerCase.call(x)正在运行,因为JavaScript使用<$ c $执行调用时,c> toLowerCase as 。这就是调用的方式(这与你在每个函数上找到的 Function.prototype.call 相同)知道你想要它执行 toLowerCase

toLowerCase.call(x) is working because JavaScript uses toLowerCase as this while executing call. This is how call (which is the same Function.prototype.call you find on every function) knows you want it to execute toLowerCase.

调用传递到另一个函数丢失该引用,所以不再引用 toLowerCase

Passing call into another function loses that reference, so this no longer refers to toLowerCase.

这篇关于为什么不[[A“,”B“,”C“]。map(String.prototype.toLowerCase.call)有效?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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