手写apply、call、bind
apply
Function.prototype.myApply = function(context){ context = context || window context.fn = this var res if(arguments[1]){ res = context.fn(...arguments[1]) }else{ res = context.fn() } delete context.fn return res } //测试 let foo = { alue: 1 } function bar(name, age) { console.log(name) console.log(age) console.log(this.value) } bar.myApply(foo, ['kevin', 18]) // kevin 18 1
call
Function.prototype.myCall = function(context){ context = context || window context.fn = this var args = Array.from(arguments).slice(1) var res if(arguments.length>1){ res = context.fn(...args) }else{ res = context.fn() } delete context.fn return res } //测试 let obj = { name: 'xxx' }; function test(){ console.log('arguments=',arguments); // Arguments(2) [1, 2, callee: ƒ, Symbol(Symbol.iterator): ƒ] console.log('this=',this); // {name: "xxx", fn: ƒ} } test.myCall(obj,1,2);
bind
Function.prototype.myBind = function(context){ var self = this var args = Array.prototype.slice.call(arguments,1) var F = function(){} var fBind = function(){ var bindArgs = Array.prototype.slice.call(arguments) self.apply(this instanceof F ? this:context,args.concat(bindArgs)) } F.prototype=this.prototype fBind.prototype=new F()
return fBind } //测试 let obj1 = { name: 'xxx' }; function test1(name,age){ console.log('arguments=',arguments);//Arguments(2) [22, 33, callee: ƒ, Symbol(Symbol.iterator): ƒ] console.log('this=',this); // {name: "xxx"} } let f = test1.myBind(obj1,22,33) f() //需要手动执行