call和apply函数
call()语法:call (thisObj, arg1, arg2);
apply()语法:apply (thisObj, [arg1, arg2]);
- 共同点:改变this指向,并立即执行
- 区别:bind函数的参数为列表形式,apply参数为数组形式
bind函数
bind()语法:bind (thisObj, arg1, arg2);
- 不会立即执行,而是返回一个新函数,调用新函数才执行
- 改变this的指向为指定的值
- 参数为列表形式
- 方法挂载在Function.prototype上
手写bind函数(利用call或apply函数)
// bind方法挂载在Function.prototype上
Function.prototype.bindNew = function() {
// 获取参数,将参数拆解为数组
const args = Array.prototype.slice.call(arguments);
// 获取指定的this(数组第一项)
const t = args.shift(); // 删除数组的第一个元素并返回第一个元素的值
// 此处this: 谁调用就指向谁
const self = this;
// 返回一个新函数
return function() {
return self.apply(t, args);
}
}
function f1(a, b) {
console.log('this: ', this);
console.log(a, b);
}
const f2 = f1.bindNew({ x: 10 }, 1, 2);
f2();
// this: {x: 10}
// 1 2