JavaScript
为所有函数都定义了 call()
和 apply()
方法,这两个方法的应用非常广泛,作用也是一模一样的,只是参数的形式有区别而已,当然就执行效率而言,call()
的效率略高于 apply()
。
call
语法:
func.call(thisArg, arg1, arg2, ...)
thisArg
表示函数运行时使用的 this
值,arg1, arg2, ...
是参数列表,表示函数运行时需要的参数。
在构造函数继承的示例中:
/* 父类 */function Person(name, age) { this.name = name this.age = age}/* 子类 */function Student(name, age, courses) { Person.call(this, name, age) this.courses = courses}
子类构造函数需要复用父类构造函数中的代码,可利用 call()
方法调用 Person()
函数,修改执行时的 this
指向,同时,将属性 name
、age
传递给 Person
函数,以方便复用时为 Student
对象实例添加对应的属性。
apply
语法:
func.apply(thisArg, [argsArray])
apply()
方法与 call()
方法的作用一致,区别就是 call()
方法接受的是参数列表,而 apply()
方法接受的是一个参数数组或类数组对象。
将构造函数继承的示例修改一下:
/* 父类 */function Person(name, age) { this.name = name this.age = age}/* 子类 */function Student(name, age, courses) { Person.apply(this, arguments) this.courses = courses}
子类构造函数复用父类构造函数中的代码时,利用 apply()
方法调用 Person()
函数,修改执行时的 this
指向,同时,将 arguments
参数列表的类数组对象传递给 Person
函数,这在 Person
函数接收参数数量较多时很方便,但要注意的是 Student
函数参数列表的顺序需要与 Person
函数的参数顺序一致。
使用示例
求一个数组中的最大值,比如数组为:[9, 3, 18, 7, 25, 4, 1, 19, 12]
。
在 Math
对象中有 max()
方法,可求一组数中的最大值,但 max
方法不接受数组的参数,即:
Math.max(9, 3, 18, 7, 25, 4, 1, 19, 12) // 25Math.max([9, 3, 18, 7, 25, 4, 1, 19, 12]) // NaN
这时,可利用 apply()
方法来实现运算:
const array = [9, 3, 18, 7, 25, 4, 1, 19, 12]Math.max.apply(null, array) // 25
当然,随着 ES6
中 ...
(Spread syntax)的出现,我们也可以使用 call()
方法来实现了:
Math.max.call(null, ...array) // 25
甚至于直接展开数组,而不使用 call()
方法:
Math.max(...array) // 25
效率
从 ECMAScript
规范中可以查询到 apply()
与 call()
方法的算法步骤:
对比算法步骤,apply()
方法第4步中多了 CreateListFromArrayLike(argArray)
的调用,而 call()
方法第4步中是将参数列表从左向右追加到 argList
中,其它操作几乎一模一样。
CreateListFromArrayLike
算法步骤:
可以看到, CreateListFromArrayLike()
又经过了 7 步的运算。所以终归 apply()
方法在有参数列表时算法步骤比 call()
方法的步骤多。
经过反复测试,call()
方法效率略高于 apply()
方法。
在平时的开发中其实不必关注 call()
和 apply()
的性能问题,但是推荐尽可能的使用 call()
方法,特别是 ES6
的 Spread syntax
支持,call()
基本可以代替 apply()
的使用。