bind() :
方法会创建一个新函数。当这个新函数被调用时,bind() 的第一个参数将作为它运行时的 this,之后的一序列参数将会在传递的实参前传入作为它的参数。(来自于 MDN )
- 可以改变this的指向
- 可以接收其他参数的值
- 不会影响原函数的返回值
Function.prototype.bind1 = function () {
//将参数拆解为数组
const args = Array.prototype.slice.call(arguments)
//获取 this (数组第一项)
const t = args.shift()
//fn1.blind()中的fn1
const self = this
//返回一个函数
return function () {
return self.apply(t,args)
}
}
function fn1(a, b, c) {
console.log('this', this);
console.log(a, b, c);
return 'this is fn1'
}
const fn2 = fn1.bind1({ x: 100 }, 10, 20, 30)
const res = fn2()
console.log(res);