0

I am wondering, is it possible to emulate the Function.prototype.call method?

I've implemented an emulation of bind(), the Douglas Crockford example is well known, by using apply() in a wrapper function.

Can I do the same for call(), without using apply, or bind? It's not something I would use of course in the real world, but just out of academic interest!

So far I havn't been able to figure this one, except using implicit binding - which has obvious drawbacks

'use strict';

// obj to bind as this, params is an array of parameters
function customCall( obj, params ){

  var funToCall = this;
  obj.funToCall = funToCall; // Implicit binding

  obj.funToCall(...params); // Obviously not a good idea
}

var objA = {
  a: "objA value"
};

function test(num1, num2){
  debugger;
  console.log(this.a);
  console.log(num1, num2);
}

test.customCall = customCall;
test.customCall(objA, [1,2]) //objA value, 1 2
Drenai
  • 11,315
  • 9
  • 48
  • 82
  • Sorry but I'ma little confused of what you are asking. In your code, you have added a property to `obj`, so you are calling a function associated to object and not prototype. Also please refer [call vs apply](http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply). Ideally every task that can be done using `apply` can be achieved using `call`. So *Can I do the same for call()*, **Yes**. – Rajesh Jan 12 '17 at 12:20
  • @Rajesh I fully understand call, apply, and call vs apply:-) Maybe have a re-read of the question:-) – Drenai Jan 12 '17 at 12:25
  • AFAIK you can't arbitrarily set `this` without using `call` `apply` or `bind`. – Jonathan Gray Jan 12 '17 at 12:51
  • You can via implicit binding e.g. object property call, which is how the example works. 'new' and arrow functions also set this. But don't think they'd help here – Drenai Jan 12 '17 at 12:56
  • @Brian Implicit binding is how it's supposed to work. Hence why I stated "arbitrarily". – Jonathan Gray Jan 13 '17 at 07:19
  • I've never seen the word arbitrarily used to describe explicitly setting this. But yeah, agree – Drenai Jan 13 '17 at 08:05

0 Answers0