源碼來襲:call、apply手寫實現與應用

關於this指向能夠了解個人另外一篇博客:JavaScript中的this指向規則html

 1、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

 2、call與apply的手寫實現

 思路:app

show.call(obj);
//代碼能夠被如下三行代碼替代
obj.show = show;
obj.show();
delete = obj.show;

call手寫實現:this

 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手寫實現:spa

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 }
相關文章
相關標籤/搜索