Last active
March 19, 2019 07:07
-
-
Save gaterking/a373a2d3f57aa6c5693fed9d43a593b0 to your computer and use it in GitHub Desktop.
call/apply/bind
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 手动实现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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 手动实现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; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 手动实现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