简介及区别
call 和 apply作用一模一样,区别仅在于传参列表不同。
apply
apply 接受两个参数,第一个参数指定了函数体内 this 对象的指向,第二个参数为一个带下标的集合,这个集合可以为数组,也可以为类数组。
类数组:
- 对象本身要可以存取属性;
- 对象的 length 属性可读写。
call
bind 参数类型和 call 相同,不过它不会执行函数,而是修改 this 后返回一个新的函数
var func = function( a, b, c ){
alert ( [ a, b, c ] );
};
func.apply( null, [ 1, 2, 3 ] );
func.call( null, 1, 2, 3 );
动手实现apply函数
Function.prototype.apply = function (context) {
var context = context || window;
var args = arguments[1] || [];
context.fn = this;
var result = context.fn(...args);
delete context.fn;
return result;
}
call 和 bind 是包装在 apply 上面的语法糖:
Function.prototype.call = function( context ){
var argus = [];
for (var i = 1; i < arguments.length; i++) {
argus.push(arguments[i]);
}
this.apply(context, argus);
};
Function.prototype.bind = function( context ){
var self = this; // 保存原函数
// 返回一个新的函数
return function(){
// 执行新的函数的时候,会把之前传入的 context // 当作新函数体内的 this
return self.apply( context, arguments );
}
};
用途
- 改变 this 指向
- 借用其他对象的方法: 在操作类数组(比如 arguments) 的时候,可以找 Array.prototype 对象借用方法Array.prototype.push.call(a, 'first' )