回答

收藏

call 和 apply 和有什么不一样?

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

Function.prototype.apply()使用和Function.prototype.call()调用函数有什么区别?* f0 K& w3 a/ o1 G
    var func = function() {  alert('hello!');};func.apply();` 对比 `func.call();) }$ l9 n8 ]$ K$ P$ }
上述两种方法之间是否存在性能差异?什么时候最好使用?callover apply,反之亦然?# K8 F' Q, `: k; e
                                                               
7 t* e! ^6 B4 U/ Z    解决方案:                                                                2 I9 \8 v/ n6 n
                                                                区别在于apply,函数你可以arguments作为数组调用;call要求列出参数。有用的助记符是    A代表数组,C代表逗号”。( s  n) A/ ^1 Q# [4 ~3 S
请参阅 MDN 关于apply和call的文档。
; _5 N' `& H1 Q& Z6 O  ^) v- j+ M5 Y伪语法:/ C/ E9 o0 T! p7 E7 K4 M" R: `
theFunction.apply(valueForThis,arrayOfArgs)theFunction.call(valueForThis,arg1,arg2,...)从 ES6 开始,还可以spread您可以在这里使用数组和函数call检查兼容性。- s7 H+ d' h: w9 g
示例代码:& q4 P& h, i. B8 |
    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  R, E3 z( g5 H8 F, G0 t' p  s
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则