1、实现apply/call
function foo(name,age){
console.log(this,name,age)
}
Function.prototype.hyexec= function(thisArg,otherArgs){
thisArg = (thisArg === null || thisArg === unndefined) ? window:Object(thisArg)
Object.defineProperty(thisArg,"fn",{
enumerable:false,
configurable:true,
value:this
})
thisArg.fn(...otherArgs)
delete thisArg.fn
}
Function.prototype.hyapply = function(thisArg,otherArgs){
this.hyexec(thisArg,otherArgs)
}
Function.prototype.hycall = function(thisArg,...otherArgs){
this.hyexec(thisArg,otherArgs)
}
foo.hyapply({name:"why"},["james",25])
foo.hyapply(123,["why",18])
foo.hycall({name:'why'},"james",25)
foo.hycall(123,"why",18)
foo.hycall(null,"kobe",30)
2、bind实现
function foo(name,age,height,address){
console.log(this,name,age,height,address)
}
Function.prototype.hybind = function(thisArg,...otherArgs){
thisArg = thisArg === null || thisArg ===undefined ? window : Object(thisArg)
Object.defineProperty(thisArg,"fn",{
enumerable:false,
configurable:true,
writable:false,
value:this
})
return (...newArgs) =>{
var allArgs = [...otherArgs,...newArgs]
thisArg.fn(...allArgs)
}
}
var newFoo = foo.hybind("abc","kobe",30)
newFoo(1.88,"北京市")