View Full Version : OOP passing variables

07-23-2012, 09:56 PM
Having trouble passing the variables name age species and breed into function displayBadge from Pets.

Any help would be appreciated! Thank you in advance!:thumbsup:

species = prompt("What species of a pet did you bring today?",ES);
breed = prompt("What is the breed of your pet?",ES);
age = prompt("How many years old is your pet?",ES);
name = prompt("What is your pet's name",ES);

var competingPet = new Pet(name, age, species, breed);


function Pet(theName, theAge, theSpecies, theBreed) {
this.petName = theName;
this.petAge = theAge;
this.petSpecies = theSpecies;
this.petBreed = theBreed;

this.displayBadge = displayBadge;

function displayBadge() {
document.write(petName + " is a " + petBreed + " " + petSpecies +
" and is " + petAge + " years old.");

07-24-2012, 06:35 AM
a) an object’s methods belong into its prototype (i.e. the prototype property of its constructor function) and should reference the object properties, not some global variables from outside.

b) the displayBadge() function will eat your page if called after page load (an often overlooked side effect of document.write())

07-24-2012, 09:37 PM
You cannot reference an object's properties inside a method by using simple identifiers in Javascript, unlike some other programming languages. Use the this keyword inside a method to refer to the object on which the method was called.

function displayBadge() {
document.write(this.petName + " is a " + this.petBreed + " " + this.petSpecies +
" and is " + this.petAge + " years old.");

Old Pedant
07-24-2012, 11:17 PM
Look at the "last edited" comment at the bottom of the first post.

This thread should be closed as RESOLVED.