Nov

29

In the previous post, I demonstrated the basic concept of Object Creation. Today let’s see the hidden power behind the simple basic concept. In the last exmaple, we add a function element to the newObject object using the method below:

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

When adding functions to an object, you can also use existing functions. Let’s go ahead
and add that sayLoudly() function now as an example:

function sayLoudly() {
alert(this.firstName.toUpperCase());
}

To attach the above function independent from the newObject class, you just need to write:

newObject.sayLoudly = sayLoudly;

Note the use of the this keyword within the function sayLoudly. The object it refers to will be dynamically calculated at runtime. Therefore, in this case, it will point to the object newObject When sayLoudly() is part of another object, the keyword this will then reference that other object. This runtime binding is another very powerful feature of JavaScript’s object-oriented implementation, since it allows for sharing of code, and, it’s a form of inheritance. Let’s write a function to alert sayLoudly() or sayName() base on a variable called whatVolume.

var newObject = new Object();
newObject.firstName = "james";
newObject.sayName = function() {
alert (this.firstName);
}
function sayLoudly() {
alert(this.firstName.toUpperCase());
}
newObject.sayLoudly = sayLoudly;
var whatFunction;
var whatVolume;
whatVolume = 2;
if (whatVolume ==1) {
whatFunction = "sayName";
}
if (whatVolume ==2) {
whatFunction = "sayLoudly";
}
newObject[whatFunction]();

Below is the demo page, enjoy!

http://www.lab.highub.com/javascript/object-creation-adv.html



Similar Posts

Comments

Name (required)

Email (required)

Website

Speak your mind

Sponsors




Links