实现call
- call 会立即调用函数
- 第一个参数是指定对象,后面的都是传入的参数
- 如果第一个参数传入 undefined、null 会指向window
Function.prototype.myCall = function (thisArg, ...args) {
const fn = this
thisArg = thisArg !== undefined && thisArg !== null ? Object(thisArg) : window
thisArg.fn = fn
const result = thisArg.fn(...args)
delete thisArg.fn
return result
}
function sum(num1, num2) {
console.log(this)
return num1 + num2
}
const res = sum.myCall('123', 20, 30)
console.log(res)
实现apply
- apply 会立即调用函数
- 第一个参数是指定对象,传参是以数组的方式
- 如果第一个参数传入 undefined、null 会指向window
Function.prototype.myApply = function (thisArg, arrArg) {
const fn = this
thisArg = (thisArg !== undefined && thisArg != null) ? Object(thisArg) : window
thisArg.fn = fn
arrArg = arrArg || []
const res = thisArg.fn(...arrArg)
delete thisArg.fn
return res
}
function sum(num1, num2) {
return num1 + num2
}
const res = sum.myApply("123", [20, 30])
console.log(res);
实现bind
- 不会立即调用函数,会返回一个变更后的函数
- 第一个参数是指定对象,后面的都是传入的参数
- 如果第一个参数传入 undefined、null 会指向window
- 可以分开传参,const foo = bind(this,1,2);foo(3,4)
Function.prototype.myBind = function (thisArg, ...arrArgs) {
const fn = this
thisArg = (thisArg !== null && thisArg !== undefined) ? Object(thisArg) : window
function proxyFn(...args) {
thisArg.fn = fn
const res = thisArg.fn(...arrArgs, ...args)
delete thisArg.fn
return res
}
return proxyFn
}
function foo(num1, num2) {
console.log(this);
console.log(num1, num2);
return num1 + num2
}
// foo.myBind("123", 10, 20)
const bar = foo.myBind("123", 10, 20)
console.log(bar());