我如何使用Function.prototype.call而不是apply?



我试图使用一个'Function.prototype '。调用'而不是'Function.prototype。申请ie8使用

function testLog(){
console.log.apply(console, arguments) // not supported 'apply' ie8
}
testLog(1,2,3) // 1,2,3

Function.prototype。在ie8中不支持"Apply",

function testLog(){
// console.log.call(console, ...arguments)  //not supported 'spread operator' ie8
console.log.call(console, Array.prototype.slice.call(arguments));
}
testLog(1,2,3) // [1,2,3]  

我尝试使用'Function.prototype. '。,但是我遇到了麻烦,因为ie不支持扩展操作符。

如何使用'Function.prototype.call'获得1,2,3而不是[1,2,3]?


附加解释

我没有找到console.log在ie8中不支持。

,但Console.log是一个示例。我希望重点应该放在"申请"one_answers"呼叫"上

另外,当前运行在ie8上,'call'是启用的,'apply'仍然不可用。

[使用]https://caniuse.com/?search=ES%205.1%3A%20generic%20array-like%20object%20as%20arguments

[电话]https://caniuse.com/?search=JavaScript%20built-in%3A%20Function%3A%20call

正如T.J. Crowder能够在他的回答(现已删除)和评论中测试和确认的那样,Internet Explorer 8中的console.log没有(完整的)Function原型。

我刚刚验证了,虽然IE8支持Function.prototype.applycall的JavaScript函数,它支持console.log上。(console是主机提供的。主机提供的函数不一定是完整的JavaScript函数,它们在旧版本的IE中非常奇怪。

<子>T.J.克劳德- 2021-08-23 08:43:41 UTC

这意味着直接在console.log上调用.apply不起作用。尽管如此,它仍然是一个函数,所以它应该表现得像一个函数,即使它没有公开您期望它具有的方法。

为了获得期望的结果,您可以使用表达式

console.log.apply(console, arguments);

可以使用Function.prototype.call:

间接调用console.log上的apply
Function.prototype.apply.call(console.log, console, arguments);

调用方法apply和上下文console.log,并提供consolearguments作为参数,看起来就像console.log.apply(console, arguments)

这也适用于现代浏览器,当然,它适用于任何接受任意数量参数的函数,例如Math.max:Function.prototype.apply.call(Math.max, Math, arguments)

注意,apply中的"数组"必须是一个合适的Arrayarguments对象,而不是任何通用的类数组对象(如{ 0: 4, 1: 2, length: 2 })。这是因为,正如MDN证实的那样,IE8不支持像arguments这样的通用数组类对象。ECMAScript 5.1的附录E更具体一点:在IE8中,只允许Arrays和arguments对象作为apply的第二个参数。

最新更新