let obj2 = { name:'bluejoker', say:function(...args){ console.log(args); console.log(this); } } obj2.say.myCall(obj1,obj1.name,obj1.say) //['iso','it is you and me'] //obj1
2.apply
apply()方法会将this指向传入的第一个参数,并接受一个参数数组。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
let obj1 = { name:'iso', say:'it is you and me' }
let obj2 = { name:'bluejoker', say:function(...args){ console.log(args); console.log(this); } } obj2.say.apply(obj1,[obj1.name,obj1.say]) //['iso','it is you and me'] //obj1
Function.prototype.myApply = function (context,arr){ context = context ? context : Window//同上 context.fn = this//同上 if(!arr){ context.fn()//判断arr是否为空或为null,undefined等,是则立刻调用context.fn() }elseif(Array.isArray(arr)){//判断是否为数组 context.fn(...arr)//是则传递参数 }else{ returnTypeError("arr is not a Array") }//不是则返回异常 delete context.fn//同上 }
let obj1 = { name:'iso', say:'it is you and me' }
let obj2 = { name:'bluejoker', say:function(...args){ console.log(args); console.log(this); } } obj2.say.myApply(obj1,[obj1.name,obj1.say]) //['iso','it is you and me'] //obj1
3.bind
bind()方法会将this指向传入的第一个参数,并接受任意形式的参数,同时,bind()返回一个新的函数。(这个新函数 保留原函数的原型链。这意味着,如果我们用 bind 生成的函数作为构造函数(通过 new 调用),新创建的实例应该能够访问原函数的原型上的方法。)