Javascript Objects: Survival 101

So there are a lot of ways to create an object in Javascript.

If you have some helper functions that should be called statically from time to time all over your script you might do something like this:

var myObjectLiteral = {

   variable1: "my variable",

   function1: function() {
      return this.variable1;
   }

};

Think of object literals as a toolbox for your page, not really a full blown class. Not to shabby but a but heavy on the performance side, and it doesn’t really provide you any of the benefits of polymorphism, I.E. let’s say I created a class called shape. This class can have a circle or square in it. The shapes can be different colors. All the shapes need to know if they are a circle or a square and what color they might be…

Something like this might be what you need:

var shape = function(shape, color) {

    // private vars
    var color = color,
        shape = '';

    // construct
    var init = function() {
        if(shape == 'square'){
            makeSquare();
        } else {
            makeCircle();
        }
    };

    // private
    var makeSquare = function() {
        shape = 'square';
    };

    var makeCircle = function() {
        shape = 'circle';
    };

    // public
    this.getShape = function() {
        return shape;
    };

};

You might call this by saying:

var blueCircle = new shape('circle', 'blue');

var redSquare = new shape('red', 'square');

// would return "circle"
console.log(blueCircle.getShape());

That’s great, it’s still not totally optimized yet (that was using the “module” pattern). You might write the same object using the contructor or “prototype” pattern:

var shape = function(shape, color) {    this.shape = shape;    this.color = color;};
shape.prototype.getShape = function() {    return this.shape;};

var shape = function(shape, color) {
    this.shape = shape;
    this.color = color;
};

shape.prototype.getShape = function() {
    return this.shape;
};

Finally, if you’re looking for something optimized, a good workhorse is what’s known as function caching…

Basically, its a modular design pattern but your functions are cached and ready to be garbage collected if the scope is right:

// function caching
var getShapeFunc = function() {
    return this.shape;
};

var initFunc = function(color, shape) {
    this.color = color,
    this.shape = shape;
};

var shape = function () {
    return {
        init: initFunc,
        getShape: getShapeFunc
    };
};

Ok that’s it for me, I’m going to bed. Pretty cool shit though right? There’s also a great resource that explains some of this further:

http://addyosmani.com/resources/essentialjsdesignpatterns/book/#designpatternsjavascript

And an awesome Javascript performance article here:

http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.