Jump to content

call method of object while looping thru instances of objects


roberto68
 Share

Recommended Posts


function Person (name, age) { this.name = name;    this.age = age;this.printMe = new function(){ return console.log("name" + Person.name + "age" + Person.age);      };}// Now we can make an array of peoplevar family = new Array();family[0] = new Person("alice", 40);family[1] = new Person("bob", 42);family[2] = new Person("michelle", 8);family[3] = new Person("timmy", 6);// add the last family member, "timmy", who is 6 years oldfor (i=0; i < family.length; i++){ family[i].printMe;   }

It's simple I wanna print name and age but this way it isn't working




			
				


	Edited  by roberto68
	
	

			
		
Link to comment
Share on other sites

Try removing "new" from the printMe function inside function Person and adding () to family.printMe();

 

Also in the console.log output, instead of Person.name and Person.age, have instead this.name and this.age.

 

Oh, also for the sake of good practice, don't forget the keyword 'var' in the for loop declaration. :good:

Edited by Don E
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...