JavaScript: cloning objects with the call() function

The call() function allows us to execute a method designed to work in a specific context inside a new context passed as an argument to this method. This function accepts two types of arguments: the context of execution and the actual arguments passed to the invoked method. Suppose that we have a singleton class like the following:

var Class = {
 
     method: function(property) {
     
         alert(property);
     
     },
     
     getInstance: function(obj) {
     
        return new obj();
     
     }
 
};

The first method alerts any property passed as its argument, whereas the other method returns a new instance of an object. We can use this class together with the call() function as follows:

function AnotherClass() {
  
  this.foo = 'Foo';
  
}
 
var myClass = new AnotherClass();
 
Class.method.call(myClass, myClass.foo); // 'Foo'

alert(Class.getInstance.call(myClass, myClass.constructor)); // [object Object]
 
var anotherMyClass = Class.getInstance.call(myClass, myClass.constructor);
 
alert(anotherMyClass.foo); // 'Foo'

As you can see, our singleton class works as an interface that performs two tasks:

  1. returns a property of another class
  2. clones the class itself

The latter point is interesting. We've passed the constructor property as the second argument of the getInstance() method invoked, in turn, with the call() function. The result is a cloning of the AnotherClass object.

Leave a Reply

Note: Only a member of this blog may post a comment.