Using the .call() method in a Javascript object to call methods from another object

So I have an object called toolset that I use to encapsulate some methods that other objects can use. For example I have a method to send an ajax request and on success call back a specific method in another object.

so for example I have toolset like so

function Toolset(){
  this.AjaxUrl = 'someurl';
}
Toolset.prototype.Request = function(req,callback,sender){ //SENDER IS IMPORTANT, MORE AHEAD
  //Send my request 
  // args can be any data returned by your request we assume a string for this example but it can be anything
  callback.call(sender,args);
}

Now I can instantiate toolset and pass it to any object that needs to make an ajax request. For example:

function Foo(Toolset)
{
   this.TS = Toolset;
   this.ReceivedData ='';
}
Foo.prototype.DoSomething = function()
{
  var req = 'somedata';
  this.TS.Request(req,this.OnReceived,this); // NOTE WE USE this AS THE SENDER
}
Foo.prototype.OnReceived = function (Args)
{
   this.ReceivedData = Args;
   //Do Something Else
}

And using foo

var TS = new Toolset();
var myFoo = new Foo(TS);
myFoo.DoSomething();

Now, some explaining:
In

Toolset.prototype.Request = function(req,callback,sender)

I am asking for a sender variable, then when using Request()

this.TS.Request(req,this.OnReceived,this);

I pass ‘this’ which references the object that is making the request.

This is very important because when we use

callback.call(sender,args);

if we just used ‘this’ instead of sender, the method we passed would be called but it would be called under the Toolset object and we wouldn’t have access to any of the methods and properties in foo.

so this

this.ReceivedData = Args;

would throw an undefined error for this.ReceivedData
using sender makes sure the callback method passed is executed under the correct object, in this case myFoo

  1. A coworker stored production assets in Dropbox. Chaos ensued.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.