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模拟实现
最新推荐文章于 2025-07-16 22:25:14 发布
本文介绍如何使用JavaScript模拟实现Function.prototype中的bind、call和apply方法,通过具体代码示例详细解释了这些方法的工作原理。
1816

被折叠的 条评论
为什么被折叠?



