Object Oriented JavaScript – Quick Reference

Object Definition and Creation

Constructor-based Creation

var Example = function(val) {
    this.foo = val;
}

var example = new Example('something');

// Although it's unusual to see to this technique, new instances of
// Example may be created using Example's built-in constructor property:
var anotherExample = new example.constructor('something else');

JSON-based Creation

var example = {
    foo: 'something'
};

Non-shared Member Attributes

var Example = function() {
    // Each instance of Example gets its own copy of the foo() function.
    this.foo = function() { ... };
};

Shared Member Attributes

var Example = function() {};

// Add a shared foo() function attribute to all past and future instances
// of Example.
Example.prototype.foo = function() { ... };

Note that when declaring a shared function on an object’s prototype, any constructor-scoped varaibles will not be accessible from within the shared function – e.g. foo, declared inside the Example constructor function, will not be directly available from within foo().

Function Access to the Parent ‘this’

var Example = function() {
    var that = this;
    this.foo = '';

    var bar = function(val) {
        // Because inner functions have their own 'this' attribute, the
        // parent object's 'this' attribute is obscured. A common
        // workaround is to assign 'this' to a variable (conventionally
        // named 'that' at parent scope:
        that.foo = val;
    }
 };

Object Inheritance

JavaScript is a very flexible language and although it does not have the classical inheritance mechanisms of, say, Java and C++, there are a number of commonly used JavaScript idioms that are used to provide object inheritance. Two common techniques are shown below.

Start with a base object, Animal:

var Animal = function() { ... };
Animal.prototype.getLegCount = function() { ... };

Prototype Chaining

var Cat = function() { ... };
Cat.prototype.meow = function() { ... };

// Prototype chaining allows Cat to inherit from Animal.
Cat.prototype = new Animal();

// New instances of Cat are created using the ‘new’ operator.
var fluffy = new Cat();

Parasitic Inheritance

var Dog = function() {
    var that = new Animal();

    // parasitic extension of Animal...
    that.woof = function() { ... };

    return that;
};

// New instances of Dog are created using the 'new' operator.
var spot = new Dog();

Because the `Dog` constructor function returns an object, the new operator will use that object as its result, assigning it to the variable spot, above (see Step 9 of Construct in ECMAScript Language Specification).