Function.prototype.myCall = function(context, ...rest) {
context = context || window
context.fn = this
const res = context.fn(...rest)
delete context.fn
return res
}
Function.prototype.myApply = function(context, arr) {
context = context || window
context.fn = this
const res = context.fn(...arr)
delete context.fn
return res
}
Function.prototype.myBind = function(context, ...rest1) {
const fn = this
return function(...rest2) {
return fn.myCall(context, ...rest1, ...rest2)
}
}
const person = {
name: 'xxx',
age: 20
}
const sayHello = function(toName) {
console.log(`${this.name} say hello to ${toName}`)
}
sayHello.myCall(person, 'kity')
sayHello.myApply(person, ['kity'])
const fn = sayHello.myBind(person, 'kity')
fn()
console