Skip to content

Instantly share code, notes, and snippets.

@ositowang
Created April 2, 2019 21:23
Show Gist options
  • Save ositowang/357dd2bdcebeb854e22beb91c02fb3ee to your computer and use it in GitHub Desktop.
Save ositowang/357dd2bdcebeb854e22beb91c02fb3ee to your computer and use it in GitHub Desktop.
a simple version of the call() in javascript
/**
* 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