【问题标题】:how can i use Function.prototype.call instead of apply?我如何使用 Function.prototype.call 而不是 apply?
【发布时间】:2021-08-23 18:00:32
【问题描述】:

我正在尝试在 ie8 中使用“Function.prototype.call”而不是“Function.prototype.apply”。

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

'Function.prototype.apply'在ie8中不支持,

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.call”,但遇到了麻烦,因为 ie 不支持扩展运算符。

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


补充说明

我没有发现 ie8 不支持 console.log。

但是, console.log 是作为示例编写的。我希望重点应该放在“申请”和“打电话”上

另外,目前在 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

【问题讨论】:

  • apply 应该是 supported since IE 5.5console.log.apply(console, Array.prototype.slice.call(arguments)); 应该可以正常工作。你确定你需要担心的不是console.log吗?你真的需要支持 IE 8 吗?
  • 我想知道它是否在 IE8 中的 console.log 上不受特别支持。 console 在 IE8 和 IE9 中非常非常奇怪(在 IE10 中甚至有点奇怪)。编辑:果然没有(也不是call)。
  • @SebastianSimon - IE8 很奇怪。尽管它支持applycall,但它console.log 上支持它们(或者可能是其他主机提供的功能)。您可能知道这一点,但对于潜伏者来说:主机提供的函数不必是真正的 JavaScript 函数,它们只需是可调用的。旧 IE 提供的可调用对象不具备完整的 Function 功能。

标签: javascript function internet-explorer-8 function.prototype


【解决方案1】:

作为 T.J. Crowder 能够在他的answer (now deleted) 和 cmets 中进行测试并确认,Internet Explorer 8 中的console.log 没有(完整的)Function 原型。

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

——T.J. Crowder, 2021-08-23 08:43:41 UTC

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

为了得到你期望用表达式得到的结果

console.log.apply(console, arguments);

你可以使用Function.prototype.call间接调用applyconsole.log

Function.prototype.apply.call(console.log, console, arguments);

这会使用上下文console.log 调用方法apply,并提供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 的 Appendix E 更具体一点:在 IE8 中,只允许 Arrays 和 arguments 对象作为 apply 的第二个参数。

【讨论】:

  • 我还可以确认您不需要slice 电话,因为applyarguments 很满意。这是一个谨慎的版本,它首先尝试现代方法,然后使用回退:pastebin.com/BHWRGQTx 它在 IE8 上有效(第一个 try 抛出,第二个 try 不抛出)。
猜你喜欢
  • 2021-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-08
  • 2016-06-13
  • 2023-03-03
相关资源
最近更新 更多