1

I'm trying to take an existing object in Javascript and rewrite it as a module. Below is the code I'm trying to rewrite as a module:

var Queue = {};
Queue.prototype = {
    add: function(x) {
        this.data.push(x);
    },
    remove: function() {
        return this.data.shift();
    }
};
Queue.create = function() {
    var q = Object.create(Queue.prototype);
    q.data = [];
    return q;
};         

Here's my attempt at making a module:

var Queue = (function() {

    var Queue = function() {};

    // prototype
    Queue.prototype = {
        add: function(x) {
            this.data.push(x);
        },
        remove: function() {
            return this.data.shift();
        }
    };

    Queue.create = function() {
        var q = Object.create(Queue.prototype);
        q.data = [];
        return q;
    };


    return Queue;
})();

Is this right? And if it is, how do I call upon it in other functions or areas in my js code. I appreciate all help!

1
  • @IHateLazy, I forgot to change it to Queue, my bad Dec 9, 2012 at 22:35

2 Answers 2

1

It seems a little pointless to have an empty constructor function, then use a property on that constructor function as effectively a constructor.

Why not just take advantage of the constructor...

var Queue = (function() {

    var Queue = function() {
        if (!(this instanceof Queue))
            return new Queue();

        this.data = [];
    };

    Queue.prototype = {
        add: function(x) {
            this.data.push(x);
        },
        remove: function() {
            return this.data.shift();
        }
    };

    return Queue;
})();

Or if you prefer to use Object.create, I'd do this instead:

var Queue = (function() {

    var Queue = function() {
        var o = Object.create(proto);

        o.data = [];

        return o;
    };

    var proto = {
        add: function(x) {
            this.data.push(x);
        },
        remove: function() {
            return this.data.shift();
        }
    };

    return Queue;
})();

In both cases, you'd just use Queue to create the new objects.

var q = Queue();

Technically the first one should use new Queue(), but it has the instanceof test to allow new to be elided.

1
  • Thank you for your help! And thanks for the tip of just skipping the Object.create Dec 9, 2012 at 22:49
0

If you are trying to modularize your code, try ConversationJS. It allows you to keep your code base extremely decoupled by escaping traditional function calls: https://github.com/rhyneandrew/Conversation.JS

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.