call、apply 和 bind
- call 和 apply: 会调用原来的函数并改变其 this 的指向,this指向的是传递过来的第一个参数
- bind:返回一个新的函数,在新的函数内部会调用用原来的函数;并改变其 this 的指向,this 为传递的第一个参数
- call、apply、bind 的第一个参数若为 null 或 undefined 的话,那么 this 的指向将变为 window
- call 和 apply 的区别就是传递的参数不同
- call可以接受多个参数
- apply 只能传入两个参数,第二个参数
往往是数组
call 的简单实现
Function.prototype.myCall = function (context, ...args) {
// 防止与函数发生命名冲突的问题,以至于覆盖原来的函数
let fn = Symbol('fn');
// 处理 context 为 null 或 undefined 的问题
const ctx = context || window;
ctx[fn] = this;
const result = ctx[fn](...args);
delete ctx[fn];
return result;
}
apply 的简单实现
apply 和 call 很相似,只是在处理参数的方便略有不同
Function.prototype.myApply = function (context, args = []) {
let fn = Symbol('fn');
const ctx = context || window;
ctx[fn] = this;
const result = ctx[fn](...args);
delete ctx[fn];
return result;
}
bind 的简单实现
Function.prototype.myBind = function (context, ...arg1) {
return (...arg2) => {
const fn = Symbol('fn');
const ctx = context || window;
ctx[fn] = this;
const result = ctx[fn](...arg1, ...arg2);
delete ctx[fn];
return result;
}
}