Skip to content

Instantly share code, notes, and snippets.

@gaterking
Last active March 19, 2019 07:07
Show Gist options
  • Save gaterking/a373a2d3f57aa6c5693fed9d43a593b0 to your computer and use it in GitHub Desktop.
Save gaterking/a373a2d3f57aa6c5693fed9d43a593b0 to your computer and use it in GitHub Desktop.
call/apply/bind
/**
* 手动实现apply方法
*
*/
function fakeApply(context, arr) {
context.applyFn = this;
var args = [];
for (var i = 0; arr && i < arr.length; i++) {
args.push('arr[' + i + ']');
}
var result = eval('context.applyFn('+ args +')');
delete context.applyFn;
return result;
}
if (!Function.prototype.apply) {
Function.prototype.apply = fakeApply;
}
Function.prototype.fakeApply = fakeApply;
/**
* 手动实现bind方法
*
*/
function fakeBind(context) {
var fn = this;
var args = [];
var preArgs = [];
for (var i = 1; i < arguments.length; i++) {
preArgs.push(arguments[i]);
args.push('preArgs[' + (i - 1) + ']');
}
return function () {
for (var i = 0; i < arguments.length; i++) {
args.push('arguments[' + i + ']');
}
context.bindFn = fn;
var result = eval('context.bindFn(' + args + ')');
delete context.bindFn;
};
}
if (!Function.prototype.bind) {
Function.prototype.bind = fakeBind;
}
Function.prototype.fakeBind = fakeBind;
/**
* 手动实现call方法
*
*/
function fakeCall(context) {
context.callFn = this;
var agrs = [];
for (var i = 1; i < arguments.length; i++) {
agrs.push('arguments['+ i +']');
}
var result = eval('context.callFn(' + agrs + ')');
delete context.callFn;
return result;
}
if (!Function.prototype.call) {
Function.prototype.call = fakeCall;
}
Function.prototype.fakeCall = fakeCall;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment