回答

收藏

call 和 apply 和有什么不一样?

技术问答 技术问答 416 人阅读 | 0 人回复 | 2023-09-11

Function.prototype.apply()使用和Function.prototype.call()调用函数有什么区别?
9 }( L. K, U; B7 @# C7 Y
    var func = function() {  alert('hello!');};func.apply();` 对比 `func.call();* }8 P, K2 ]/ Y: L  l9 ~7 @
上述两种方法之间是否存在性能差异?什么时候最好使用?callover apply,反之亦然?
; l, s5 v: y: U# n                                                                2 H6 M. R/ `; R* W& w
    解决方案:                                                               
$ n" D+ r0 [. \% n# N  g                                                                区别在于apply,函数你可以arguments作为数组调用;call要求列出参数。有用的助记符是    A代表数组,C代表逗号”。$ e/ u- n: @3 x9 r+ Q
请参阅 MDN 关于apply和call的文档。9 N. |7 z3 u0 k0 W! z
伪语法:
, z( ~3 f) d: @! ~4 `9 o7 w  o& JtheFunction.apply(valueForThis,arrayOfArgs)theFunction.call(valueForThis,arg1,arg2,...)从 ES6 开始,还可以spread您可以在这里使用数组和函数call检查兼容性。, I9 O+ ]5 Y# b% x0 Y  \
示例代码:
8 r6 V" U* k$ h$ \/ ^- H
    function theFunction(name,profession)    console.log("My name is "   name   " and I am a "   profession  ".");}theFunction("John","fireman");theFunction.apply(undefined,["Susan","school teacher"]);theFunction.call(undefined,"Claude","mathematician");theFunction.call(undefined,...["Matthew","physicist"]); // used with the spread operator, j0 |8 H8 A+ o* h
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则