JavaScript in Object-Oriented Way

Here’s my presentation slide during barcamp phnom penh 2009:

progress bar using JavaScript

Here’s a littile progress bar I’ve created using JavaScript. I’ve use JavaScript setInterval() to increase the progress bar & clearInterval() to stop progress bar.

//Create dom
var bar = document.createElement("div");
progressBar = document.createElement("div");
with(bar.style){
    width = "200px";
    height = "10px";
    position = "absolute";
    border = "1px solid #949DAD";
};

with(progressBar.style){
    width = "0px";
    height = "100%";
    background = "#D4E4FF none repeat scroll 0 0";
};

bar.appendChild(progressBar);
document.body.appendChild(bar);

//start setInterval
var x = window.setInterval(
	function(){
                progressBar.style.width = parseInt(progressBar.style.width) + 5 + "px";
            //stop interval when progress bar width = 200
            if(parseInt(progressBar.style.width) == 200) clearInterval(x);
	},
	40
);

JavaScript Inheritance: modify property in parent class

In the following code, there’s a problem which is faced when we’re using inheritance through prototype.

Now, we have a parent class Person, and we have a child class Student which inherit from Person. As a default, we want to set gender to “Male”.

var Person = function(){
    this.object = {"name": "", "gender": "Male"};
}

Person.prototype.sayHi = function(){
    console.log ("Hi! I am " + this.object.name);
}

Person.prototype.sayGender = function(){
    console.log ("I am " + this.object.gender);
}

var Student = function(){}
Student.prototype = new Person();

var victoria = new Student();
victoria.object.name = "Vitoria";
victoria.object.gender = "Female"
victoria.sayHi();
victoria.sayGender();

var sam = new Student();
sam.object.name = "Sam";
sam.sayHi();
sam.sayGender();

here’s the result:

Hi! I am Votoria
I am Female
Hi! I am Sam
I am Female

As we see, the default gender “Male” has been alter to “Female”. we can prevent the default gender in the Person class to be altered by adding “Person.apply(this);” Student class.

After added, the code will look like this:

var Person = function(){
    this.object = {"name": "", "gender": "Male"};
}

Person.prototype.sayHi = function(){
    console.log ("Hi! I am " + this.object.name);
}

Person.prototype.sayGender = function(){
    console.log ("I am " + this.object.gender);
}

var Student = function(){
    Person.apply(this);
}
Student.prototype = new Person();

var victoria = new Student();
victoria.object.name = "Vitoria";
victoria.object.gender = "Female"
victoria.sayHi();
victoria.sayGender();

var sam = new Student();
sam.object.name = "Sam";
sam.sayHi();
sam.sayGender();

here’s the result:

Hi! I am Votoria
I am Female
Hi! I am Sam
I am Male

Javascript Array.filter

filter(): runs a function on every item in the array and returns an array of all items for which the function returns true.

Syntax:

var filteredArray = array.filter(callback[, thisObject]);

var arrayObj = [
            {"uuid": "C3EF0958-F530-0001-4793-1A3917C011DB","name" : "borey", "position": "developer"},
            {"uuid": "f47ac10b-58cc-4372-a567-0e02b2c3d479", "name": "sok", "position": "designer"},
            {"uuid": "C3EF0948-3F50-0001-8E28-C560102CD090", "name": "seiha", "position": "developer"},
            {"uuid": "C3EF094D-CD90-0001-3567-139E1BF01B14", "name": "dara", "position": "manager"},
            {"uuid": "C3EF0953-FCD0-0001-A745-1C3019401ED7", "name": "meta", "position": "developer"}
            ];

var updateValue = function(uuid, newObj){
    var obj = arrayObj.filter(function(obj){ return obj.uuid == uuid;  })[0];
    obj.uuid = newObj.uuid;
    obj.name = newObj.name;
    obj.position = newObj.position;
};

var displayArrayObjectValue = function(arrayObject){
    var length = arrayObject.length;
    for( var i = 0; i < length; i++){
        console.log(arrayObject[i].uuid + ' '+arrayObject[i].name + ' '+arrayObject[i].position);
    }
}

var updatedObjValue = {"uuid": "3EF099C-4940-0001-A0F8-F92E1FC8C430", "name": "ibo", "position": "lead developer"}

console.log('before change: ');
displayArrayObjectValue(arrayObj);

updateValue("C3EF0958-F530-0001-4793-1A3917C011DB", updatedObjValue);

console.log('after change: ');
displayArrayObjectValue(arrayObj);

The code above will update the value of object which has uuid = “C3EF0958-F530-0001-4793-1A3917C011DB”

javascript setInterval & clearInterval

An example to demonstrate how start interval & stop it using javascript.

var x = window.setInterval(
	function(greeting, name){
		var m = document.createElement("div");
                with(m.style){
                    height = "2px";
                    width = "50px";
                    position = "relative";
                    backgroundColor= "green";
                }
                document.body.appendChild(m);
	},
	1000,
	"hello",
	"world",
        document.body.onclick = function(){
	    clearInterval(x)
        }
);

Create object in javascript using JSON

Here’s how we create javascript object using Javascript Object Notation (JSON). After the code below is executed, it would show alert windows with text “Borey Lim”

//script to demonstrate creating object in javascript using JSON

var objectDemo = {
	firstName: "",
	lastName: "",
	displayName : function(){
		alert(this.firstName + " " + this.lastName);
	}
}

objectDemo.firstName = "Borey";
objectDemo.lastName = "Lim";
objectDemo.displayName();

flexible constructor in JavaScript

Javascript provides flexible constructor. Below are sample code that implement the flexible constructor:

var Student = function(_department, _course, _year){
	department = _department || "";
	course = _course || "";
	year = _year || "";

	this.set_department = function(_department){
		department = _department;
	}

	this.set_course = function(_course){
		course = _course;
	}

	this.set_year = function(_year){
		year = _year;
	}

	this.display_information = function(){
		console.log("Information of the student:");
		console.log("Department: " + department);
		console.log("Course: " + course);
		console.log("Year: " + year);
	}
}

//constructor
var obj_student = new Student("Computer Information Scince", "ICT", "2");
obj_student.display_information();

var another_obj_student = new Student();
another_obj_student.set_department("Technology");
another_obj_student.set_course("BIS");
another_obj_student.set_year("Foundation");
another_obj_student.display_information();

Sample output:

Information of the student:
Department: Computer Information Scince
Course: ICT
Year: 2
Information of the student:
Department: Technology
Course: BIS
Year: Foundation

Javascript inheritance

Inheritance in javascript can be implemented easily using the concept of mixin. Below is an exmple to demonstrate javascript inheritance:

ClassA = function(){
	this.display = function(){
		console.log("here's a display function in ClassA");
	}

	this.str = function(){
		return "string in ClassA";
	}
}

ClassB = function(){
	ClassA.call(this);

//overriden method
	this.str = function(){
		return "string in ClassB";
        }
}

//instantiate object of ClassB
obj = new ClassB();

//calling display method from ClassA
obj.display();

//this will invoke str method in ClassB NOT in ClassA
console.log(obj.str());
here’s a display function in ClassA
string in ClassB string in ClassB

Javascript: delete property from object & element from array

As we are working with object or array, sometimes, we need to delete it’s property of element. Below is an example of a simple way to do it.


var display_before = function (str){
    return "before delete " + str;
}

var display_after = function (str){
    return "after delete " + str;
}

var obj = {x:12, y:15};
console.log(display_before("obj.x") + " " + obj.x);

//delete property x from object
delete obj.x;
console.log(display_after("obj.x") + " " + obj.x);

//delete array[2]
var array = [2, 4, 6, 8, 10]
console.log(display_before("array: ") + array);

array.splice(2,1);    //delete value 6 from array
console.log(display_after("index 2 from array: ") + array);

Sample result (in firebug plugin):

before delete obj.x 12
after delete obj.x undefined
before delete array: 2,4,6,8,10
after delete index 2 from array: 2,4,8,10

Overloading method in javascript

Since i’m going to write some code for the client side, I have to start learning OO javascript. What makes me surprise the most is how it is written. here are some codes i have tested:


as you can see in the code, i only create one function, however i can call in different ways. This is how dynamic Javascript is. Really Really dynamic!!!!