JavaScript is the most flexible and widely used language in current era of Internet, nobody expected JavaScript to grow this fast and wide, hence I say JavaScript is kind of under-developed but over used technology. But that doesn’t take the beauty of flexibility away from JavaScript even though security remains major concern in its implementation. Every day it keeps me interesting with it’s abilities, every time I think why did I miss that part it. In all it’s the most flexible language for OO coding, here is the small example which shows how you can easily organize and maintain JavaScript code.
Say I have to define 2 functions walk and run. you can define them as follows.
function walk(){
// do walking
}
function run(){
// do running
}
If you are defining this function as part of a Man class, code looks like this
var Man=function(){
//….
};
Man.prototype=function(){
// do walking
};
Man.prototype.run=function(){
// do running
};
/* Usage */
var ravi=new Man();
ravi.walk();
ravi.run();
If you want class encapsulated in one declaration you can do
var Man=function(){
//….
};
Man.prototype={
walk:function(){
// do walking
},
run:function(){
//do running
}
}
What’s next you can add a method to Function object that can be used to declare methods.
Function.prototype.method = function(name, fn) {
this.prototype[name] = fn;
};
var Man= function() {
//do something
};
Man.method(‘walk’, function() {
//do walking
});
Man.method(‘run’, function() {
//do running
});
As we saw earlier, flexibility of JavaScript is enviable, here every thing is an object (except primitive data types) and you can add attributes and methods to these Objects at any point of time, execution. You can even add methods and attributes to Functions as well. Here is an example:
function displayError (message){
displayError.numTimesExecuted++;
alert(message);
}
displayError.numTimesExecuted = 0;
here is another example with prototype:
function Man(weight, height){
this.height = height;
this.weight = weight;
}
Man.prototype={
getHeight:function(){
return this.height;
},
getWeight:function(){
return this.weight;
}
}
/* Initiating the class */
var ravi = new Man (80,164);
var suresh = new Man (75,169);
/* add new method to Class */`
Man.prototype.getGreeting=function(){
return "Hi your height and weight is " + this.getHeight() +" and " + this.getWeight() + " respectively";
}
ravi.getGreeting();
//output "Hi your height and weight is 164 and 80 respectively"