let obj = {
a:3,
fn:function(str=null){
console.log(str +' --- '+ this.a)
}
}
Function.prototype.mybind = function(obj){
return () =>{
this.mycall(obj)
}
}
Function.prototype.mycall = function(obj = (typeof window === 'undefined' ? undefined : window ),...arg){
if(typeof this !== 'function'){
throw this + 'is not a function'
}
let fn = Symbol('fn')
obj[fn] = this
const result = obj[fn](...arg)
delete obj[fn]
return result
}
Function.prototype.myapply = function(obj = (typeof window === 'undefined' ? undefined : window ),arg = []){
if(typeof this !== 'function'){
throw this + 'is not a function'
}
let fn = Symbol('fn')
obj[fn] = this
const result = obj[fn](...arg)
delete obj[fn]
return result
}
let o1 = {
a:6,
b:3,
fn:function(){
console.log(this.b)
}
}
obj.fn.myapply(o1,['myapply']) // 6
o1.fn() // 3
obj.fn.mycall(o1,'mycall') // 6
let test = function (){
console.log(this.a)
}.mybind(o1)
test.call(obj) // 6
自己实现bind,call,apply
最新推荐文章于 2025-04-03 22:42:37 发布