HTML and CSS Reference
In-Depth Information
You might want to go further and allow a user to have many pets. You can do
this by creating an array of pets within the user model. You will have to create
several new methods to manage the pets array from outside of the user object.
addPet will add a single pet to the pet array.
getPet gets a single pet at a specific index from the pet array.
removePet removes a single pet using an index value.
setPets sets the pet array using an array of pets, overwriting
the existing pet array.
getPets retrieves all of the pets assigned to a user object.
The new changes to the user object are as follows.
/**
* Now that you can have multiple pets, it doesn't make sense to add it to
* the constructor
*/
var user = function user(name, password){
var _name = null,
_password = null,
_pets = [], // The default value is now an array instead of null
_self = this;
this.setName(name);
this.setPassword(password);
// favoritePet is not part of the constructor anymore, so it doesn't need to
be set
name = null;
password = null;
...
/**
* Adds a pet to the pet array
*/
this.addPet = function(pet){
// You can add object validation here before adding to the pet array
_pets.push(pet);
}
/**
* Gets a pet from the array at a specific index
*/
this.getPet = function(index){
return _pets[index];
Search WWH ::




Custom Search