Object-Oriented Programming in JavaScript
Functions are also used to represent classes when doing object-oriented JavaScript. There are several possible ways to write object-oriented JavaScript code, but they all turn around the concept of the “Function” class:
[source:javascript]
function Thing() {
var privateField = “PRIVATE”;
var self = this; // See below for more explanations about “this” :)
var privateMethod = function() {
alert('Private methods can be called from public methods');
self.anotherPublicMethod();
}
this.publicField = "PUBLIC";
this.publicMethod = function() {
privateMethod();
alert('From the public method;\nthis is a public value: ' + this.publicField +
'\nand this is a private value: ' + privateField);
};
this.anotherPublicMethod = function() {
alert('You need a trick to call this from a private method!');
};
}
// Creating a new instance of “Thing”
var thingy = new Thing();
thingy.publicMethod(); // you can also call thingy“publicMethod”;
[/source] Continue reading →