實現(xiàn)原理:當意圖把一個函數(shù)的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');