// apply实现
Function.prototype.applyA = function (_this, arr) {
if (!_this) _this = Object.create(null);
_this.fn = this;
// 参数字符串化处理
var res = eval("_this.fn(" + arr + ")");
delete _this.fn;
return res;
}
Function.prototype.bindA = function (_this) {
if (!_this) { _this = Object.create(null) };
var self = this;
var resFn = function () {
var arg = arguments;
var pa = [];
// 参数数组化,原始js实现
for (var i = 0; i < arg.length; i++) { pa.push(arg[i]) };
return self.applyA(_this, pa);
};
return resFn;
};
function sum(a, b) {
return this.v + a + b;
};
sum.bindA({v:'10'},1,2);
实现主要关键步骤
1.创建隐式调用,改变this指向为绑定的this
2.原生实现参数转换通过遍历和eval