概念:相同点:call,apply都是改变this指向,bind也是
不同点:call,apply传参列表不同,bind在后边绑定this是谁。
其中运用到了eval函数,建议项目中不要使用,会修改作用域。
实现自己的call函数:
Function.prototype.myCall = function () {
var ctx = arguments[0] || window;
ctx.fn = this;
var args = [];
var len = arguments.length;
for (var i = 1; i < len; i++) {
args.push('arguments[' + i + ']');
}
//args-->['arguments[1]','arguments[2]',...]
var result = eval('ctx.fn(' + args.join(',') + ')');
delete ctx.fn;
return result;
}
实现自己的apply函数:
Function.prototype.myApply = function (ctx, arr) {
var ctx = ctx || window;
ctx.fn = this;
if (!arr) {
var result = ctx.fn();
delete ctx.fn;
return result;
} else {
var len = arr.length,
args = [];
for (var i = 0; i < len; i++) {
args.push('arguments[' + i + ']');
}
var result = eval('ctx.fn(' + args.join(',') + ')');
delete ctx.fn;
return result;
}
}
实现的自己的bind函数:
Function.prototype.myBind = function(){
var ctx = arguments[0] || window,
self = this,
arrPro = Array.prototype,
args = arrPro.slice.call(arguments,1);
return function(){
self.apply(ctx,arrPro.concat.call(args));
}
}