关于this指向可以了解我的另一篇博客:JavaScript中的this指向规则。
var value = "window";var obj = { value:"obj"}fonction show(){ console.log(this.value); }show();//windowshow.call(obj);//objshow(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);//6show.call(obj,sum1,sum2);//7show.apply(obj,[sum1,sum2]);//7
思路:
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 }