5

I want to decouple the creation of JavaScript objects from the code that is using it so that I have the flexibility of replacing one object implementation with other object implementation having same signature without touching much of the code. In order to achieve this I come up with the concept of Repository and a Factory Method to create objects. Here is the implementation:

//The Factory Method
function ObjectFactory() {}
ObjectFactory.create = function (o) {
    var args = [].slice.call(arguments, 1);

    function F() {}
    F.prototype = o.prototype;
    var instance = new F();
    o.apply(instance, args);
    return instance;
};

//The Repository
var Repository = {
    'invitation': Invitation,
    'message': Message
};

//Usage
var inv = ObjectFactory.create(Repository["invitation"], "invitation", "invitation body", "Sender");
var msg = ObjectFactory.create(Repository["message"], "message", "message body");
var inv2 = ObjectFactory.create(Repository["invitation"], "invitation2", "invitation body2", "Sender");

This pattern is working for me but before I go ahead and implement this code in my project I want to know are there any pitfalls(failure of pattern to create objects, performance bottlenecks - if I'll create 5-10 objects of 200 to 1000 lines of code) using this approach. I am returning to JavaScript after working on server side code for a long time so I am not very confident of my solution. Also, I could have used ES5 Object.create but the customer is stuck with IE8 and FF3.6 browsers for now.

Thanks

1 Answer 1

3

Just use Object.create() along with an ES5 shim like this: https://github.com/kriskowal/es5-shim/blob/master/es5-shim.js

It does most of what you want, and does things the ES5 way for when that actually becomes standard. Given the common case of using one object as the prototype for another, it works fine in all browsers.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.