Object Oriented JavaScript - Quick Reference

Object Creation

Constructor-based Creation

function Example(attr) {
    this.attr = attr;
    // Other member attributes and methods.
}

var example = new Example();

// New instances may now also be created using the built-in constructor
// attribute:
var anotherExample = new example.constructor()

JSON-based Creation

var example = {
    attr: null
    // Other member attributes and methods.
}

Inheritance

function Example(attr) {
    this.attr = attr;
    this.foo = function() {}
    // Other member attributes and methods.
}

// Extend Example by adding the bar function to all instances.
Example.prototype.bar = function() {}

Member Attributes

Public Member Attributes

function Example(attr) {
    // Public member attribute accessible by member and non-member functions.
    this.publicAttr = attr;
}

Private Member Attributes

function Example(attr) {
    // Private member attribute only accessible by private and privileged member
    // functions.
    var publicAttr = attr;
}

Member Functions

Public Member Functions

function Example() {
}

Example.prototype.publicFoo = function() {
    // Public functions:
    // * May be called by either member or non-member functions.
    // * Can access public member attribute, but not private member attributes.
}

Private Member Functions

function Example() {
    function privateFoo() {
        // Private functions:
        // * Are only accessible to other private or privileged member functions.
        // * Can access private member attributes.
    }
}

Privileged Member Functions

function Example() {
    this.privilegedFoo = function() {
        // Privileged members:
        // * Can be accessed by either member or non-member functions.
        // * Can access public and private member attributes.
    }
}

Private Member Function Access Of Public Member Attributes

function Example(attr) {
    var that = this;
    this.publicAttr = attr;

    function privateFoo(val) {
        // Because inner functions have their own 'this' attribute, the instance
        // attribute 'this' of the parent function is obscured. Creation of a
        // private member, 'that', and pointing it to the 'this' instance
        // attribute is the convention used as a work-around.
        that.publicAttr = val;
    }

Labels: , ,

Bookmark and Share
Subscribe to this blog
rss news feed icon