javascript
Function.prototype.myBind = function(context) {
if (typeof this !== 'function') {
return
}
const args = [...arguments].slice(1)
const fn = this
return function Fn() {
// 判断函数作为构造函数的情况,这个时候需要传入当前的函数的this给apply调用,其余情况都传入指定的上下文对象
const target = this instanceof Fn ? this : context
return fn.apply(target, args.concat([...arguments]))
}
}
function setName(name) {
this.name = name
}
const obj = {
age: 1
}
const setName1 = setName.bind(obj)
setName1('test')
console.log('正确结果', obj)
const setName2 = setName.myBind(obj)
setName1('miome')
console.log('正确结果', obj)