iamjerryyeung

Saturday, January 07, 2006

javascript OOP

http://www.javascriptkit.com/javatutors/oopjs.shtml

JavaScript and Object Oriented Programming (OOP)
Credits: This tutorial is written and contributed by Tim Scarfe. Edited by JavaScriptKit.com for content/ structure. Please see footnote for more information on author.

JavaScript is an excellent language to write object oriented web applications. It can support OOP because it supports inheritance through prototyping as well as properties and methods. Many developers cast off JS as a suitable OOP language because they are so used to the class style of C# and Java. Many people don't realize that JavaScript supports inheritance. When you write object-oriented code it instantly gives you power; you can write code that can be re-used and that is encapsulated.

What's so great about objects?
Objects work so well because they act just like real life objects- objects have properties and methods. So if we were talking about a lamp, a property of it may be its height or width, say 12cm. A method of it may be to shine (an action). And when it's shining, its brightness property would be of a greater value than when it wasn't.

JavaScript gives you the ability to make your own objects for your own applications. With your objects you can code in events that fire when you want them to, and the code is encapsulated. It can be initialized any amount of times.

Creating objects using new Object()
There are several ways to create objects in JavaScript, and all of them have their place. The simplest way is to use the new operator, specifically, new Object():

<
person = new Object()
person.name = "Tim Scarfe"
person.height = "6Ft"

person.run = function() {
this.state = "running"
this.speed = "4ms^-1"
}

//-->
We define a custom object "person," then add to it its own properties and method afterwards. In this case, the custom method merely initializes two more properties.

Creating objects using Literal Notation
Another inline way of defining an object is via literal notation. Supported in JavaScript1.2 and above, it's a more robust form of creating an object on the fly:


Literal notion can contain arrays or arbitrary JavaScript expressions or values.

While using the new operator or literal notion to create a custom object is both simple and logical, the biggest shortcoming is that the result is NOT reusable- we cannot easily initialize different versions of the created object. For example with the first demonstration above, if the person's name is not "Tim Scarfe", we would need to redefine our entire object just to accommodate this change.

0 Comments:

Post a Comment

<< Home