回答

收藏

call 和 apply 和有什么不一样?

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

Function.prototype.apply()使用和Function.prototype.call()调用函数有什么区别?: F. q7 e& U- @0 G
    var func = function() {  alert('hello!');};func.apply();` 对比 `func.call();4 @& c# }0 W9 V2 u* q# H2 A" q
上述两种方法之间是否存在性能差异?什么时候最好使用?callover apply,反之亦然?
% g- }) ~2 z& s- o  K( W6 w) b                                                                * K, F8 [/ O0 t
    解决方案:                                                                $ R4 x. [2 Q5 |' u. V# u
                                                                区别在于apply,函数你可以arguments作为数组调用;call要求列出参数。有用的助记符是    A代表数组,C代表逗号”。
4 v+ m: I1 s" g8 H5 T* A. U" m请参阅 MDN 关于apply和call的文档。
1 t9 ~) V. P. ?( p2 z+ \+ s伪语法:  n; Z) a& w$ M; E. N
theFunction.apply(valueForThis,arrayOfArgs)theFunction.call(valueForThis,arg1,arg2,...)从 ES6 开始,还可以spread您可以在这里使用数组和函数call检查兼容性。
7 R6 A% {. ]. `9 W6 r& ^4 W示例代码:
0 G% _& v) G7 d( ?2 d4 w
    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' \! y+ k% {+ h6 w
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则