Joe Crawley
Joe Crawley

Reputation: 725

Creating and using Modules in Javascript

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!

Upvotes: 1

Views: 822

Answers (2)

Andrew Rhyne
Andrew Rhyne

Reputation: 5090

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

Upvotes: 0

I Hate Lazy
I Hate Lazy

Reputation: 48761

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.

Upvotes: 1

Related Questions