關於this指向能夠了解個人另外一篇博客:JavaScript中的this指向規則。html
var value = "window"; var obj = { value:"obj" } fonction show(){ console.log(this.value); } show();//window show.call(obj);//obj show(null);//window
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
思路: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 }