JS:.apply(null,arguments)——为什么我的函数被调用一次,而console.log被调用多次

JS: .apply(null, arguments) -- Why is my function called once, whilst console.log called many times?

本文关键字:调用 一次 log console 我的 apply null arguments JS 为什么 函数      更新时间:2024-04-04

我正在阅读优秀的Eloquent Javascript的第5章。

我正在尝试理解.apply函数。

JavaScript函数有一个应用方法。您向它传递一个参数数组(或类似数组的对象),它将使用这些参数调用函数。

给出的例子是:

function transparentWrapping(f) {
  return function() {
    return f.apply(null, arguments);
  };
}

我自己尝试了一下,写下了这样的话:

function doIt(f) {
    return function(arg) { return f.apply(null, arguments) };
}
doIt(console.log)("Hello there!","Hi!","Hello!!", "Testing");

输出为:

Hello there! Hi! Hello!! Testing

但是,如果我把console.log换成我自己的功能:

function logIt(arg) {
    console.log(arg+"'r");
}
doIt(logIt)("Hello there!","Hi!","Hello!!", "Testing");

logIt()函数似乎只针对第一个参数调用。输出为:

Hello there!

为什么为每个参数调用console.log,而只为第一个参数调用logIt?

不为每个参数调用

console.log。它只是一个函数,它对传递的每个参数都做一些事情。它只被调用一次。

console.log("Hello there!","Hi!","Hello!!", "Testing");

如果多次调用:

console.log("Hello there!");
console.log("Hi!");
console.log("Hello!!");
console.log("Testing");

…然后输出会将每个字符串放在一个单独的行上。

另一方面,logIt只对您传递的第一个参数执行任何操作。

logIt("Hello there!","Hi!","Hello!!", "Testing");