2

I ́m trying to understand how Function.prototype.call() works. I know what it does, and I can work with it, but I ́m curious about how this method is implemented.

Is it possible to write a javascript-method from scratch that does exactly the same?

Ram
145k16 gold badges174 silver badges201 bronze badges
asked Aug 7, 2014 at 14:38
6
  • 3
    It's a built-in function - to the best of my knowledge there's no way to implement it in pure JS. Commented Aug 7, 2014 at 14:40
  • 1
    The JavaScript runtime has the ability to call functions in general, and part of that job is setting up the value of this. From that perspective there's really nothing surprising about the existence of .call() and .apply(); they pretty much have to exist anyway if the thing is going to work. Commented Aug 7, 2014 at 14:42
  • @Alnitak thank you, I was trying to find information about this for hours today, got kind of obsessed. You probably saved the rest of my day :D Commented Aug 7, 2014 at 14:43
  • @DominikGabor with JS treating functions as first class objects then as Pointy suggests it's essential that the language have an intrinsic method (no pun intended) of invoking a function object. That method is .call (and .apply) Commented Aug 7, 2014 at 14:45
  • FYI: github.com/mozilla/gecko-dev/blob/… Commented Aug 7, 2014 at 14:47

1 Answer 1

2

It's not possible to "unwrap" variable arguments without eval. If it's fine with you, you can try this:

function myCall(fun, obj) {
 var args = [].slice.call(arguments, 2);
 var arglist = args.map(function(_, n) { return "args[" + n + "]" }).join(',');
 obj._tmp = fun;
 return eval("obj._tmp(" + arglist + ")")
}

Example:

foo = {
 x: 123
}
bar = function(y) { return this.x + y }
console.log(myCall(bar, foo, 444))
answered Aug 7, 2014 at 14:51
Sign up to request clarification or add additional context in comments.

2 Comments

In modern JS, you can copy from the arguments array and use apply.
So that apply is the fundamental function and call can be implemented in terms of it

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.