-
在JavaScript中每个Function对象都有apply和call方法,apply和call用于修改某个函数的this指向,而this的指向永远指向最后调用它的对象。不同的是,apply接收的是参数数组,call接收的是参数列表。
-
apply语法:
func.apply(thisArg, [argsArray])// argsArray是数组或类数组 call语法:func.call(thisArg, arg1, arg2, ...)// arg1,arg2是参数 -
thisArg是必选参数,替换func函数中this的对象。当在非严格模式下,thisArg指定为
null或者更undefined时,func的this指向是全局对象。args和arg1是可选参数,该值为null或undefined时表示不传参数。 -
用法
- 实现继承:
function Person(name, position){ this.name = name; this.position = position; this.showMsg = function(){ console.log('姓名:' + this.name + ', 职位:' + this.position) } } function Programmer(name, position){ // Programmer类继承Person类,Programmer类的this替换了Person类的this指向 Person.apply(this, arguments); // arguments参数的类数组对象 } let man = new Programmer('吴*', '前端开发'); man.name; // 吴* man.showMsg(); // 姓名:吴*, 职位:前端开发- apply可以将传进去的参数数组转化成func的参数列表,根据这个特性可以进行一些转换操作。
Math.max(arg1, arg2, ...)只能传入参数列表,如果需要获取数组的最大值,需要进行转化:Math.max.apply(null, [arg1, arg2, ...]),或者使用es6的扩展运算符:Math.max(...[agr1, arg2, ...])- 通过Array.prototype.push合并数组:
Array.prototype.push.apply(arr1, arr2)合并数组arr1和arr2,arr1调用push方法,arr2通过apply转化成参数列表push进arr1中。
-
参考链接: