function fn(a, b) {
console.log('a', a); // 10
console.log('b', b); // 20
console.log('this', this) // {x: 1}
return 'hello'
}
const res = fn.myCall({x: 1}, 10, 20)
console.log(res) // hello
const res1 = fn.myApply({x: 1}, [10, 20])
Function.prototype.myCall = function () {
const [t, ...others] = Array.prototype.slice.call(arguments);
const self = this; // fn 调用的 myCall, 这里的 this 是 fn
// fn(others) 但是 this指向有问题
t.fn = self;
const res = t.fn(others) // 接收 fn 的返回值
delete t.fn;
return res;
}
Function.prototype.myApply = function () {
const [t, others] = Array.prototype.slice.call(arguments);
const self = this; // fn调用的 myApply, this 指向 fn
// fn(...others) 这样调用 this 指向 window
// 现在想让 this 指向 t
t.fn = self;
const res = t.fn(...others);
delete t.fn;
return res;
}
Function.prototype.myBind = function () {
const self = this; // 谁调用的myBind, this就指向谁, fn
const [t, others] = Array.prototype.slice.call(arguments);
return function () {
return self.call(t, ...others);
}
}
js 手写call、apply、bind
于 2022-05-29 20:08:27 首次发布