Tuesday, March 31, 2015

Javascript OOP

Javascript is a prototypical langaage. Its OOP is achieved by prototype instead of class. Prototype is kind of like decorator patten, that decorates a initially bare object with more functionalities.

Some links to Javascript OOP:
The most common syntax for defining a class is [3]:

if (typeof (classA == "undefined")) {

    // Another short-hand way of defining this class:  function classA() { ... }
    var classA = function() {
        this.property1 = 1;  // A public variable. Defined with "this.". To access, use "this.".
        var secret = 2;  // A private variable. Defined with "var". To access, don't use "this.".

        // A private method.
        // Another short-hand way of defining this:  function dec () { ... }
        var dec = function() {
             if (secret > 0) {
                secret -= 1;
            }
        }

       
        // A privileged method. Can access private variables and methods. Accessible to outside.
        // Defined with "this.".
        // Another way of defining this:  function getInfo() { ... }
        this.getInfo = function() {
            return secret + this.property1;
        }     
    }

    // A public method.
    classA.prototype.getColor = function() { return 'green'; }
}

To create an instance you do:

var objectA = new classA();

To inherit from classA you do something like this [2]:

function classB() {
    this.setValue(value);

classB.inherits(classA);

Promiscuous multiple inheritance is possible but hard and may suffer from name collision.

Other related concepts include swiss inheritance, parasitic inheritance etc.


No comments:

Blog Archive

Followers