javascript, object orientation, inheritance Part 1
The documentation about the more advanced features of javascript are rather poor. So instead of complaining I’ll put something together myself.
The basic function-based approch to javascript coding is basic and well documented. Let’s skip this part. I’ll assume you have some knowlange of obect orientated programing and understand the difference between object and class. The class beeing the blueprint, the object a concreate instance to work with.
Object orientation in JS is proberbly different to what most coders are familiar with. And there are several ways to do it.
About Javascipt variables
JS is a loosly typed language. A variable may either be primitive (eg an integer) an object (eg String) or a function. You can assign any of those types to variables. Objects have properties. So you can go along setting properties to functions. Further you can go along on a object assign a property of type function to it – just so, on the fly. As it is a loosley typed language you can even assign a function with a different signature to an objects property. Now show me how to do that in your language.
Lets start with a object literal.
I like to think of it as kind of inline singelton. You can go ahead and write the object directly. No class required, just rolling it as you go along. Perfect for a fire-and-forget object to pass to another function – much like jquery and extjs expect it as a function parameter. Or a singelton – that is an object that can only have one and only one instance. Like a Validator. Write one, call anywhere. I admit the syntax looks a bit strange :
var Validator = {
isNumeric: function(val) {
return !isNaN(val);
},
isInt: function(val) {
var res = false;
var tested = val.toString();
if ( val.match(/^\d+$/) ) {
return true;
}
return res;
}
}
if (! Validator.isNumeric(“tintifax”)) {
alert(“not an Number”)
}
So between the {} of Validator you write the property followed by a “:” and then the value – in this case the function. After each variable definition you enter a “,” with the exception of the last entry. As soon as the code is parsed you have an object literal. Thats the quickest and easiest way to write objects.
Now for classes
function Car(name) {
// a public property. you can access it from outside
this.name = “noname”;
// nasty hack for accessing private vars out of public context
var self = this;
// contructor code here – init the cars name
if (name) {
this.name = name;
}
// a private property, No way of accessing it from outside
var isCleaned = false;
// a public function
this.honk = function() {
return “basic car honk from ” + this.name + ” <br />”; // accessing public property
};
// public function getting a private property
this.getCleaned = function() {
return isCleaned;
};
// public function for setting a private property
this.setCleaned = function(isCleaned) {
this.cleaned = isCleaned;
return this.cleaned;
};
// private function
var emptyAshTray = function() {
ashtrayFull = false;
return “Ashtray of ” + self.name + ” emptied (using correct self.name )<br />”;
};
// public function calling private functions
this.clean = function () {
var retVal = “”;
retVal += emptyAshTray();
isCleaned = true;
retVal += “basic car ” + this.name + ” is now clean<br />”;
return retVal;
};
}
// alternative version for writing public methods
Car.prototype.goFast = function() {
return “car ” + this.name + ” goes fast<br />”;
};
var focus = new Car(“Focus”);
alert(“Car name: ” + focus.name);
alert(“car goes fast: ” + focus.goFast());
alert(“clean the car: ” + focus.clean())
The source code should speak for itself. Defining a Function creates the Class. Anything prefixed with “this” is public. Anything declared with “var” is private. There is a pitfall for accessing public variables from private scope (look for the hack with the self variable). There is second way of adding public variables (that can refer to functions or methods, remember) using the Cars prototype.
Explaining the Prototype
Javascript uses something called prototype-based inheritance. Every Class has a prototype shared by all its instances. You can modify the prototype to extend or alter all running instances. Read that again – modify the prototype to modify all running instances. As soon as you type String.prototype.shorten = fuction() {} all Strings have a shorten method. This is powerfull. You can not do this with object literals as they have no class, but you can alter the Validator object literal by saying Validator.isPink = function {}