手写一个bind函数
// 模拟 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)
}
}
这里连续用两个return该怎么理解,原生的object.bind()想要立刻执行需要在后面加上括号,即object.bind()(),那么想要实现类似的功能就是在手写bind函数的末尾返回一个函数,而这个函数中再返回执行self.apply(t, args),这样的话就必须实例化才能立刻立即执行bind()了~