bind()
方法创建一个新的函数,在 bind()
被调用时,这个新函数的 this
被指定为 bind()
的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
Function.prototype.myBind = function (thisArg, ...argsArray) {
//第一步,对thisArg处理,以防传进来的不是对象,基本类型的数据会转为包装对象,null和undefined会指向window
thisArg = thisArg ? Object(thisArg) : window
let fn = this
//第二步, 返回的结果为一个函数
function proxyFn(...args) {
//第三步,调用绑定的函数, 这里的this就是这个函数
thisArg.fn = fn
//第四步,比较特殊,对两个传入的参数进行合并
let finalArgs = [...argsArray, ...args]
//第五步,返回调用函数的结果
let result = thisArg.fn(...finalArgs)
delete thisArg.fn
return result
}
//第六步,返回该函数
return proxyFn
}
//测试案例1
function foo() {
console.log('foo函数被调用', this); //foo函数被调用 String {'abc', fn: ƒ}
}
foo.myBind("abc")()
//测试案例2
function sum(num1, num2, num3, num4) {
console.log(num1, num2, num3, num4, this) //10 20 40 50 String {'abc', fn: ƒ}
return num1 + num2 + num3 + num4
}
let res = sum.myBind('abc', 10, 20)
let result = res(40, 50)
console.log(result);//120
//简写版本
Function.prototype.myBind = function (thisArg, ...argsArray) {
thisArg = thisArg ? Object(thisArg) : window
thisArg.fn = this
return function (...newArgs) {
var args = [...argsArray, ...newArgs]
return thisArg.fn(...args)
}
}