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!
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…
Or if you prefer to use
Object.create, I’d do this instead:In both cases, you’d just use
Queueto create the new objects.Technically the first one should use
new Queue(), but it has theinstanceoftest to allownewto be elided.