13. 手写call, apply, bind
手写call
查看答案
Function.prototype.myCall=function(context=window){ if(typeof this !=="function"){ throw new Error("不是函数") } const obj=context||window obj.fn=this const arg=[...arguments].slice(1) res=obj.fn(...arg) delete obj.fn return res }
function f(a,b){ console.log(a+b) console.log(this.name) } let obj={ name:1 } f.myCall(obj,1,2)
obj.greet.call({name: 'Spike'})
|
手写apply(arguments[this, [参数1,参数2…..] ])
查看答案
Function.prototype.myApply=function(context){ let obj=context||window obj.fn=this const arg=arguments[1]||[] let res=obj.fn(...arg) delete obj.fn return res } function f(a,b){ console.log(a,b) console.log(this.name) } let obj={ name:'张三' } f.myApply(obj,[1,2])
|
手写bind
查看答案
this.value = 2 var foo = { value: 1 }; var bar = function(name, age, school){ console.log(name) console.log(age) console.log(school) } var result = bar.bind(foo, 'An') result(22, '家里蹲大学')
Function.prototype.bind = function(context, ...outerArgs) { var fn = this; return function(...innerArgs) { return fn.apply(context,[...outerArgs, ...innerArgs]); }
|