PDA

View Full Version : Code efficiency - prototype objects


dataphage
02-10-2003, 10:01 AM
If I have a prototype object eg:

function friend(name, birthday) {
this.name = name;
this.birthday = birthday;
this.happyBirthday = function(){
document.write('<span style="color:red"><h6>...happy birthday </h6>' + this.name + '</span>')}
}

...and I call instances of that object in an array:

var m = new Array()
m[0] = tom = new friend("Tom", 8.2)
m[1] = ali = new friend("Ali", 11.24)
m[2] = james = new friend("James", 22.4)

...every time I reference the object from the array eg:

ali.happyBirthday()

...does this re-initialize the entire object or does the array simply store the object?

dataphage
02-10-2003, 11:14 AM
With the code in the head section of an HTML doc. I put the following code in to try & sort this out:

var a=0 //test variable
function friend(name, birthday) {
a++: //increment test variable
this.name = name;
this.birthday = birthday;
this.happyBirthday = function(){
document.write('<span style="color:red"><h6>...happy birthday </h6>' + this.name + '</span>')}
}

var m = new Array()
m[0] = tom = new friend("Tom", 8.2)
m[1] = ali = new friend("Ali", 11.24)
m[2] = james = new friend("James", 22.4)

function testIt(){ //this function allows me to type in the name of a friend object and be alerted to their name and the state of the test variable
var pal = prompt("name:", "")
if(pal != "" || pal != null){
alert(eval(name).name + "\n" + a)
}

..in the body I put a button to activate the function:

<input type=button value="Test" onclick="testIt()" />

...with the above code this always seems to alert the test variable as three so the array does not re-initialize the object but just stores it. Have I got this right?