Speaking a language fluently is the key to leverage that language’s power. JavaScript has a long time being considered a difficult language to learn and use, making the Web user interface less interactive and sometimes, so boring. But in recent years, AJAX term has become so popular and many JS frameworks born to facilitate the power of JavaScript. Well-known JS frameworks which are the prominent on the web are Prototype, jQuery, Mootool, ExtJs and YUI.

Most of beginners will found difficulties getting start with these frameworks. Main reason is traditional JS programmers do not use JS heavily in their web applications or use it in an unorganized way, without any best practice pattern. While OOP is not an easy programming method, using it in JS is also headache because of JS syntax. Many programmers use JS in procedural programming style by creating functions and hooking them up with events.

When the term Web 2.0 become a standard, JS is also become a key programming skill that a web programmer need to know. The procedural JS programming should be forget and with the coming of Prototype, jQuery or other JS framework the age of JS programming began. In this post, I want to cover the basic of JS language to build a solid based for JS programmers from where they can easily taking JS frameworks into use. JavaScript can do a lot of clever things that Java and C# can’t. Some of these can help you to write better code, and some can only help you to shoot yourself in the foot more accurately! It’s worth knowing about both, either to make use of the techniques or to avoid doing them unwittingly.

Objects in JavaScript

JavaScript doesn’t require the use of objects or even functions. It is possible to write a JavaScript program as a single stream of text that is executed directly as it is read by the interpreter. As a program gets bigger, though, functions and objects become a tremendously useful way of organizing your code, and we recommend you use both.

The simplest way to create a new JavaScript object is to invoke the built-in constructor for the Object class:

var myObject=new Object();

Let’s add a property to our simple object:

myObject.shoeSize=”12″;

In a structured OO language, we would need to define a class that declared a property shoeSize or else suffer a compiler error. Not so with JavaScript. In fact, just to emphasize the array-like nature, we can also reference properties using array syntax:

myObject[’shoeSize’]=”12″;

This notation is clumsy for ordinary use but has the advantage that the array index is a JavaScript expression, offering a form of runtime reflection.

We can also add a new function to our object dynamically:


myObject.speakYourShoeSize=function(){

alert("shoe size : "+this.shoeSize);

}

Or borrow a predefined function:

function sayHello(){

alert('hello, my shoeSize is '+this.shoeSize);

}

...

myObject.sayHello=sayHello;

Note that in assigning the predefined function, we omit the parentheses. If we were to write

myObject.sayHello=sayHello();

then we would execute the sayHello function and assign the return value, in this case null, to the sayHello property of myObject.

We can attach objects to other objects in order to build up complex data models and so on:


var myLibrary=new Object();

myLibrary.books=new Array();

myLibrary.books[0]=new Object();

myLibrary.books[0].title="Turnip Cultivation through the Ages";

myLibrary.books[0].authors=new Array();

var jim=new Object();

jim.name="Jim Brown";

jim.age=9;

myLibrary.books[0].authors[0]=jim;

This can quickly become tedious (often the case where turnips are involved, I’m afraid), and JavaScript offers a compact notation that we can use to assemble object graphs more quickly, known as JSON. Have a look at it now.

Making classes

JavaScript has a concept of objects and classes but no built-in concept of inheritance. In fact, every JavaScript object is really an instance of the same base class, a class that is capable of binding member fields and functions to itself at runtime.

In JavaScript, then, we can write something that looks similar to the Java declaration

var myObj=new MyObject();

but we do not define a class MyObject, but rather a function with the same name. Here is a simple constructor:


function MyObject(name,size){

this.name=name;

this.size=size;

}

We can subsequently invoke it as follows:

var myObj=new MyObject("tiddles","7.5 meters");

alert("size of "+myObj.name+" is "+myObj.size);

One common idiom is to declare the function inside the constructor:

function MyObject(name,size){

this.name=name;

this.size=size;

this.tellSize=function(){

alert("size of "+this.name+" is "+this.size);

}

}

var myObj=new Object("tiddles","7.5 meters");

myObj.tellSize();

This works, but is less than ideal in two respects. First, for every instance of MyObject that we create, we create a new function. As responsible Ajax programmers, memory leaks are never far from our minds, and if we plan on creating many such objects, we should certainly avoid this idiom.

A prototype is a property of JavaScript objects, for which no real equivalent exists in OO languages. Functions and properties can be associated with a constructor’s prototype. The prototype and new keyword will then work together, and, when a function is invoked by new, all properties and methods of the prototype for the function are attached to the resulting object. That sounds a bit strange, but it’s simple enough in action:

function MyObject(name,size){

this.name=name;

this.size=size;

}

MyObject.prototype.tellSize=function(){

alert("size of "+this.name+" is "+this.size);

}

var myObj=new MyObject("tiddles","7.5 meters");

myObj.tellSize();

First, we declare the constructor as before, and then we add functions to the prototype. When we create an instance of the object, the function is attached. The keyword this resolves to the object instance at runtime, and all is well.

Note the ordering of events here. We can refer to the prototype only after the constructor function is declared, and objects will inherit from the prototype only what has already been added to it before the constructor is invoked. The prototype can be altered between invocations to the constructor, and we can attach anything to the prototype, not just a function:

MyObject.prototype.color="red";

var obj1=new MyObject();

MyObject.prototype.color="blue";

MyObject.prototype.soundEffect="boOOOoing!!";

var obj2=new MyObject();

obj1 will be red, with no sound effect, and obj2 will be blue with an annoyingly cheerful sound effect! There is generally little value in altering prototypes on the fly in this way. It’s useful to know that such things can happen, but using the prototype to define class-like behavior for JavaScript objects is the safe and sure route.

More about declaring Class with prototype

Interestingly, the prototype of certain built-in classes (that is, those implemented by the browser and exposed through JavaScript, also known as host objects) can be extended, too. Let’s have a look at how that works now.

Extending built-in classes

Within the web browser, DOM nodes cannot be extended in the Internet Explorer browser, but other core classes work across all major browsers. Let’s take the Array class as an example and define a few useful helper functions:

Array.prototype.indexOf=function(obj){

var result=-1;

for (var i=0;i< this.length;i++){

if (this[i]==obj){

result=i;

break;

}

}

return result;

}

This provides an extra function to the Array object that returns the numerical index of an object in a given array, or -1 if the array doesn’t contain the object. We can build on this further, writing a convenience method to check whether an array contains an object:

Array.prototype.contains=function(obj){

return (this.indexOf(obj)>=0);

}

and then add another function for appending new members after optionally checking for duplicates:

Array.prototype.append=function(obj,nodup){

if (!(nodup && this.contains(obj))){

this[this.length]=obj;

}

}

Any Array objects created after the declaration of these functions, whether by the new operator or as part of a JSON expression, will be able to use these functions:

var numbers=[1,2,3,4,5];

var got8=numbers.contains(8);

numbers.append("cheese",true);

Reflecting on JavaScript objects

In the normal course of writing code, the programmer has a clear understanding of how the objects he is dealing with are composed, that is, what their properties and methods do. In some cases, though, we need to be able to deal with completely unknown objects and discover the nature of their properties and methods before dealing with them. For example, if we are writing a logging or debugging system, we may be required to handle arbitrary objects dumped on us from the outside world. This discovery process is known as reflection, and it should be familiar to most Java and .NET programmers.

If we want to find out whether a JavaScript object supports a certain property or method, we can simply test for it:

if (MyObject.someProperty){

...

}

This will fail, however, if MyObject.someProperty has been assigned the boolean value false, or a numerical 0, or the special value null. A more rigorous test would be to write

if (typeof(MyObject.someProperty) != “undefined”){

If we are concerned about the type of the property, we can also use the instanceof operator. This recognizes a few basic built-in types:

if (myObj instanceof Array){

...

}else if (myObj instanceof Object){

...

}

as well as any class definitions that we define ourselves through constructors:

if (myObj instanceof MyObject){

...

}

If you do like using instanceof to test for custom classes, be aware of a couple of “gotchas.” First, JSON doesn’t support it-anything created with JSON is either a JavaScript Object or an Array. Second, built-in objects do support inheritance among themselves. Function and Array, for example, both inherit from Object, so the order of testing matters. If we write

function testType(myObj){

if (myObj instanceof Array){

alert("it's an array");

}else if (myObj instanceof Object){

alert("it's an object");

}

}

testType([1,2,3,4]);

and pass an Array through the code, we will be told-correctly-that we have an Array. If, on the other hand, we write

function testType(myObj){

if (myObj instanceof Object){

alert("it's an object");

}else if (myObj instanceof Array){

alert("it's an array");

}

}

testType([1,2,3,4]);

then we will be told that we have an Object, which is also technically correct but probably not what we intended.

Finally, there are times when we may want to exhaustively discover all of an object’s properties and functions. We can do this using the simple for loop:

function MyObject(){

this.color='red';

this.flavor='strawberry';

this.azimuth='45 degrees';

this.favoriteDog='collie';

}

var myObj=new MyObject();

var debug="discovering...\n";

for (var i in myObj){

debug+=i+" -> "+myObj[i]+"\n";

}

alert(debug);

This loop will execute four times, returning all the values set in the constructor. The for loop syntax works on built-in objects, too-the simple debug loop above produces very big alert boxes when pointed at DOM nodes!