javascript object literal tutorial

Object Oriented JavaScript tutorial

There are many different ways of writing javascript. Object literal notation is one of them. Before we delve into the example script below, here is a quick refresher on some things about JavaScript:

Object Declaration

Foo = new Bar(); would create a new instance of the Object Bar with name Foo.

 
    Foo = function(num1,num2){
	   return(num1 + num2);
    }
Foo is now an object.
bar = Foo(1,2);
bar is a variable that equals 3.

Some Object literal notation:

 
  var Foo = {
  	name:"John",
  	eyeColor:"green",
  	setEyeColor:function(eyeCol){
       this.eyeColor = eyeCol;
    }
  }

console.log(Foo.name); Would print out John Foo.setEyeColor("blue"); Would set the eye color to blue.

What few people realize is that it is also possible to use such literal notation in combination with JavaScript's rapid build functionality to protect methods and properties in a similar manner to Java, C++ and other object oriented languages.

Next will will take a look at a more comprehensive example.

<< Previous Page | Next Page > > Article by J C Green This article was written for non-profit educational purposes. Comments? Suggestions? Rants or raves? E-mail me using the form on this website.