JavaScript OO

ONE script to understand JavaScript OO :-)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
function MyClass () { // constructor function
var privateVariable = "foo"; // Private variable

this.publicVariable = "bar"; // Public variable

this.privilegedMethod = function () { // Public Method
alert(privateVariable);
};
}

// Instance method will be available to all instance but only load once in memory
MyClass.prototype.publicMethod = function () {
alert(this.publicVariable);
};

// Static variable shared by all instance
MyClass.staticProperty = "baz";

//...
var myInstance = new MyClass();

Clipped from StackOverflow: http://stackoverflow.com/a/1535687/1904043