Javascript中bind,call,apply模擬實現
阿新 • • 發佈:2018-12-21
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;
}