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
1 Answer 1
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
georg
216k57 gold badges325 silver badges401 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Paul Stelian
In modern JS, you can copy from the
arguments array and use apply.Paul Stelian
So that apply is the fundamental function and call can be implemented in terms of it
lang-js
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..call(and.apply)