Reputation: 31
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?
Upvotes: 2
Views: 1095
Reputation: 214959
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))
Upvotes: 2