跳到主要内容

手写 bind 函数

首先来看看 bind 函数使用

// bind 的使用
function fn1(a, b, c) {
console.log('this', this) //this {x: 100}
console.log(a, b, c) // 10 20 30
return 'this is fn1'
}
const fn2 = fn1.bind({x: 100}, 10, 20, 30)
const res = fn2()
console.log(res) //this is fn1

然后通过 Function.prototype 模拟 bind1 函数

// 手写 bind
Function.prototype.bind1 = function () {
//参数拆解为数组
const args = Array.prototype.slice.call(arguments)
//获取 this(数组第一项)
const t = args.shift()
//fn1.bind(...) 中的fn1
const self = this
//返回函数
return function () {
return self.apply(t, args)
}
}
const fn3 = fn1.bind1({x: 100}, 10, 20, 30)
const res2 = fn3() //this {x: 100} 10 20 30
console.log(res2) //this is fn1

更简洁的写法

Function.prototype._bind = function(obj, ...args) {
obj.fn = this;
return function () {
const newArgs = args.concat(...arguments);
let ret = obj.fn(...newArgs);
delete obj.fn;
return ret;
}
}