Created
April 2, 2019 21:23
-
-
Save ositowang/357dd2bdcebeb854e22beb91c02fb3ee to your computer and use it in GitHub Desktop.
a simple version of the call() in javascript
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
/** | |
* We could get the parameters with arguments in Javacript. With ES6 spread | |
* operator, you could transform it into a real list. Notes: the first | |
* parameter is the this object, so we slice it. | |
* Problems: | |
* 1. we ignore the case the context passed in is primitive type | |
* 2. we ignore the case the context passed in is null | |
* | |
* @param {Object} [context=window] | |
* @returns | |
*/ | |
Function.prototype.myOwnCallBetter = function(context = window) { | |
// get the function which calls the call/apply | |
context.fn = this; | |
let args = [...arguments].slice(1); | |
let result = context.fn(...args); | |
delete context.fn; | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment