封装call,apply,bind方法
封装call方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| function test(){ console.log(this,arguments) }
var obj1 = { name:'haohua' } var obj2 = { name:'豪华' } Function.prototype.myCall = function(){ let [context,...args] = arguments context = context||window context.__proto__.xxx = this context.xxx(...args) delete context.__proto__.xxx; }
test.myCall(obj2,12,23)
|
call和apply的区别是一个可以传多个参数,一个只能传一个参数,并且只能传数组;
封装apply方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| function test(){ console.log(this,arguments) }
var obj1 = { name:'haohua' } var obj2 = { name:'豪华' } Function.prototype.myApply = function(){ let [context,args] = arguments context = context||window args = args||[] context.__proto__.xxx = this context.xxx(...args) delete context.__proto__.xxx } test.apply(obj1,[1,2,3]) test.myApply(obj2,[4,5,6])
|
…age 扩展运算符返回的是一个数组
封装bind方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| function test(){ console.log(this,arguments) }
var obj1 = { name:'haohua' } var obj2 = { name:'豪华' }
Function.prototype.myBind = function(){ let [context,...outerArgs] = arguments return (...innerArgs)=>{ this.apply(context,outerArgs.concat(innerArgs)) } } var result1 = test.bind(obj1,10,20) result1(1,2,3) var result2 = test.myBind(obj2,30,40) result2(5,6,7)
|