上述两种方法之间是否存在性能差异?什么时候最好使用?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