Function.prototype.bindFake = function(context) {
let fn = this;
let arr = Array.prototype.slice.call(arguments, 1);
return function() {
let innerArgs = Array.prototype.slice.call(arguments);
let args = arr.concat(innerArgs);
fn.apply(context, args);
}
}
Function.prototype.callFake = function(context) {
let context = context || window;
context.fn = this;
let arr = [];
let result;
for(let i = 1; i < arguments.length; i++) {
arr.push('arguments[' + i + ']');
}
if (arr) {
result = eval('context.fn(' + arr + ')');
} else {
result = context.fn();
}
delete context.fn;
return result;
}
Function.prototype.applyFake = function(context, arr) {
let context = context || window;
context.fn = this;
let result;
if (arr) {
let args = [];
for(let i = 0; i< arr.length; i++) {
args.push('arr[' + i + ']');
}
result = eval('context.fn(' + args + ')');
} else {
result = context.fn();
}
delete context.fn;
return result;
}
Javascript中bind,call,apply模拟实现
最新推荐文章于 2024-03-31 15:50:35 发布