实现原理:当意图把一个函数的this值指向某个对象时,利用对象的属性值就可以达到目的。因为this的指向是在运行时确定的,obj.fn()的this指向obj.
Function.prototype.myCall = function(context, ...args) {
const obj = context || window; // 当context为null时,this指向window
obj.fn = this;
return obj.fn(...args);
delete obj.fn;
}
Function.prototype.myApply = function(context, args) {
const obj = context || window;
obj.fn = this;
return obj.fn(...args);
delete obj.fn;
}
Function.prototype.myBind = function(context, ...args1) {
const obj = context || window;
obj.fn = this;
return function(...args2) {
obj.fn(...args1.concat(args2))
}
delete obj.fn;
}
Function.prototype.myBind2 = function(ctx, ...args1) {
ctx = ctx || window;
const _this = this;
return function(...args2) {
_this.apply(ctx, [...args1, ...args2]);
}
}
function bar(verb, nounce) {
console.log(`${this.user}${verb}${nounce}`);
return {
user: this.user
}
}
const target = {
user: 'i'
}
bar.myCall(target, 'am', 'ivy');
bar.myApply(target, ['am', 'ivy']);
const foo = bar.myBind2(target, 'am');
foo('ivy');