JavaScript: object cloning and the Factory pattern

The Factory pattern is used in traditional OOP languages to get an instance of the current object or class. A rough implementation in JavaScript would be the following:

function A() {

    this.foo = 'Foo';
    this.getInstance = function() {
    
        return new A();
    
    };

}

The getInstance() method now returns an instance of its class. Just to reinvent the wheel, we can make some further tests to check whether we can use the returned class instance to perform object cloning:


var myA = new A();
var B = myA.getInstance();


B.prototype = A.prototype;
B.prototype.test = 'Test';

alert(B.foo); // alerts 'Foo'
alert(B.test); // alerts 'Test';
alert(A.test); // alerts 'undefined';

Associating the prototype property of the second class with a single instance of the main class results in a rough cloning of the aforementioned class. The B class correctly inherits from the A class, but the A class has not been touched. In fact, trying to access the test property we get undefined. As I said earlier, this was just a test and the result is pretty trivial.

Leave a Reply

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