25/05/2011

JavaScript hướng đối tượng giả lập một cửa sổ trình duyệt

This is a very short tutorial about Object Oriented Programming in JavaScript, in which we are going to create an object called JSWinbox that simulates a window in our browser.

There are two ways of doing OOP in JavaScript: Classical Inheritance and Prototypal Inheritance. The recommended one is Prototypal because objects will share exactly the same methods and by the classical inheritance the objects will have their own copy of each method which would be a waste of memory.

Other great features you should know about JavaScript are closures, Prototype object, and basic knowledge of the DOM. That information should be enough for you to catch the idea of this post.

How is JavaScript an OOP Language if It Does Not Use Classes?

Some folks argue that JavaScript is not a real OOP language because it is not use classes. But you know what? JavaScript does not need classes because objects inheritance from objects. JavaScript is a class free language which uses prototype to inheritance from object to object.

How Do I Create an Object in JavaScript?

There are two ways to create an object: by object literals and by constructors.

Object literals are the most recommended because it can organize our code in modules, in addition it is an object ready to go that does not need a constructor. (Very useful for singletons.)

var myDog = {
name: 24,

race: '',

getValue: function () {

return this.value;
},
}

The other way is creating object by constructors. First of all, functions are objects and functions are what we use to create constructor objects for example:

function Dog(race, name){
this.race = race;

this.name = name;

this.getRace = function(){

return this.race;
};

this.getName = function(){

return this.name;
}
}

To create an instance of the Dog object we use the following code:

var mydog = new Dog('greyhound', 'Rusty');

Now, we just need to use the object we just created. So, lets execute one of the methods. The method to execute is getRace.

mydog.getRace(); // Returns grayhound

If you need a better explanation, go to one of the links at the beginning of the article for further explanation.

SourceCode example: http://www.mediafire.com/?w91389bf211nzho

Reference: http://www.admixweb.com/2010/07/14/oop-javascript-creating-an-window-box/

Aucun commentaire: