Javascript is very powerful prototype based language. Although it is not a full blown OOP language like Java but it is an object based language.
Lets start Object Oriented Programming in Javascript
Simplest class:
function myFirstClass() {
}
var myObject = new myFirstClass();
myObject.someProperty = "This is value 1";
alert(myObject.someProperty);
We can create another instance of myFirstClass like this:
var anotherObject = new myFirstClass(); anotherObject.someProperty = "This is property of another class";
Lets take the property to the definition of our class
function myFirstClass(property1) {
this.someProperty = property1;
}
var myObject = new myFirstClass("Hello World!");
alert(myObject.someProperty);
Now we will introduce some methods of our class
function method1_myFirstClass() {
alert("This is method 1 of my first class");
}
function myFirstClass(property1) {
this.someProperty = property1;
this.method1 = method1_myFirstClass;
}
var myObject = new myFirstClass("Hello World!");
myObject.method1();
Now we will write it within our class definition
function myFirstClass(property1) {
this.someProperty = property1;
this.method1 = function() {
alert("This is method 1 of my first class");
};
}
var myObject = new myFirstClass("Hello World!");
myObject.method1();
Now we have seen a new way of writing functions. Why not write our class in this way too.
var myFirstClass = function(property1) {
this.someProperty = property1;
this.method1 = function() {
alert("This is method 1 of my first class");
};
}
var myObject = new myFirstClass("Hello World!");
myObject.method1();
I will share advanced features related to OOP javascript in my coming posts.
Stay tuned!


