源码来袭:call、apply手写实现与应用

关于this指向可以了解我的另一篇博客:JavaScript中的this指向规则

 一、call与apply的使用

  • 回顾call与apply的this指向:
var value = "window";
var obj = {
     value:"obj"
}
fonction show(){
     console.log(this.value);   
}
show();//window
show.call(obj);//obj
show(null);//window
  • 回顾call与apply的参数使用:
var sum1 = 1,
     sum2 = 2,
     c = 3,
     obj = {
          c:4
     }
function show(a,b){
     console.log( a + b + this.c);   
}
show(sum1,sum2);//6
show.call(obj,sum1,sum2);//7
show.apply(obj,[sum1,sum2]);//7

 二、call与apply的手写实现

 思路:

show.call(obj);
//代码可以被以下三行代码替代
obj.show = show;
obj.show();
delete = obj.show;

call手写实现:

 1 Function.prototype.MyCall = function(){
 2     var ctx = arguments[0] || window;
 3     ctx.fn = this;
 4     var args = [];
 5     for(var i = 1; i < arguments.length; i++){
 6         args.push(arguments[i]);
 7     }
 8     var result = eval('ctx.fn(' + args.join(",") + ')');
 9     delete ctx.fn;
10     return result;
11 }

apply手写实现:

1 Function.prototype.MyApply = function(obj,arr){
2     var ctx = obj || window;
3     ctx.fn = this;
4     arr = arr || [];
5     eval('ctx.fn(' + arr.join(",") + ')');
6     delete ctx.fn;
7 }

 

posted @ 2019-02-22 17:27  他乡踏雪  阅读(422)  评论(0编辑  收藏  举报