Nov

28

JavaScript - Object Creation

November 28, 2007 |

To learn object-oriented JavaScript programming, the first step is to get familiar with object creation. (object creation belongs to the factory paradigm of JavaScript OOP) The easiest way to create an object is to start with a new Object, Object is the base of all objects in JavaScript. So when you create an object, it is the instance of Object.

var newObject = new Object();

To add a string element to the Object instance newObject, what you need to do is:


newObject.firstName = "james";

To add a function element, what you need to do is:

newObject.sayName = function() {
alert(this.firstName);
}

To execute the object function sayName that alerts the object string firstName, all you need to do is:

newObject.sayName();

The complete code is:

var newObject = new Object();
newObject.firstName = "james";
newObject.sayName = function() {
alert(this.firstName);
}
newObject.sayName();

JavaScript actually implements all objects as associative arrays. It then puts a façade over that array to make the syntax look more like Java, or C++, using dot notation. To proof this point, let’s rewrite the code above using associative arrays.

Let’s start with adding the string element:

newObject["firstName"] = "james";

Now we can add in the function element:

newObject["sayName"] = function() {
alert(this["firstName"]);
}

And now we can execute it:

newObject["sayName"]();

The complete code is:

var newObject = new Object();
newObject["firstName"] = "james";
newObject["sayName"] = function() {
alert(this["firstName"]);
}
newObject["sayName"]();

If you try to test both scripts, you will get the same result.
Below are the links to the demo pages:
http://www.lab.highub.com/javascript/object-creation-dot-notation.html
http://www.lab.highub.com/javascript/object-creation-array.html



Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

Sponsors




Links