手写bind
// 手写bind
// args接受的1、2
Function.prototype.mybind = function(context,...args) {
// reset 接受的3
return (...reset) => this.call(context,...args,...reset)
}
function t(a,b,c) {
return a+b+c
}
const sumFn = t.mybind(this,1,2)
const sum = sumFn(3)
console.log(sum)
实现call方法
function test(a, b, c) {
console.log(this)
return a + b + c
}
const obj = {
name: 'xxx'
}
// fn.call(obj, 1,2,3)
Function.prototype.mycall = function (context, ...args) {
context = context || window
// obj.fn()
// context.fn = this
Object.defineProperty(context, 'fn', {
value: this,
enumerable: false, // 为了第二行代码 打印this的时候 不出现fn
configurable: true
})
// console.log(Object.getOwnPropertyDescriptor(context, 'fn'))
const result = context.fn(...args)
delete context.fn
return result
}
const num = test.mycall(obj, 1, 2, 3)
console.log(num)