Social Icons

Pages

Thursday, December 1, 2016

Introduction to Objects I 33/33

Methods
Methods are like functions that are associated with a particular object.
They are especially helpful when you want to either:
Update the object properties
Calculate something based on an object's properties.
Here, we have included a Circle object, with a radius property representing the circle's radius. We have implemented an areafunction which calculates the circle's area. Notice we have used Math.PI to get the π value.

Instructions
Define a method perimeter that calculates the perimeter of a circle.
function Circle (radius) {
    this.radius = radius;
    this.area = function () {
        return Math.PI * this.radius * this.radius;
    };
    this.perimeter = function () {
        return Math.PI * 2 * this.radius;
    };
}

Introduction to Objects I 32/33

function StaffMember(name, discountPercent){
this.name = name;
this.discountPercent = discountPercent;
}

var sally = new StaffMember("Sally",5);
var bob = new StaffMember("Bob",10);

// Create yourself again as 'me' with a staff discount of 20%
var me = new StaffMember("Mo", 20);

var cashRegister = {
total:0,
lastTransactionAmount: 0,
add: function(itemCost){
this.total += (itemCost || 0);
this.lastTransactionAmount = itemCost;
},
scan: function(item,quantity){
switch (item){
case "eggs": this.add(0.98 * quantity); break;
case "milk": this.add(1.23 * quantity); break;
case "magazine": this.add(4.99 * quantity); break;
case "chocolate": this.add(0.45 * quantity); break;
}
return true;
},
voidLastTransaction: function(){
this.total -= this.lastTransactionAmount;
this.lastTransactionAmount = 0;
},
// Create a new method applyStaffDiscount here
applyStaffDiscount : function(employee){
this.total -= this.total * (employee.discountPercent/100);
}
};

cashRegister.scan('eggs',1);
cashRegister.scan('milk',1);
cashRegister.scan('magazine',3);
// Apply your staff discount by passing the 'me' object
// to applyStaffDiscount

cashRegister.applyStaffDiscount(me);
// Show the total bill
console.log('Your bill is '+ cashRegister.total.toFixed(2));

Introduction to Objects I 31/33

Properties
Properties are like variables that belong to an object, and are used to hold pieces of information. Properties can be accessed in two ways:
Dot notation, with ObjectName.PropertyName
Bracket notation, withObjectName["PropertyName"] (don't forget the quotes!)
In the editor, we have brought back oursnoopy object, with a species and ageproperty.

Instructions
Set the global variable species to be snoopy's species and the variable age to be snoopy's age. For one use dot notation and the other use bracket notation!
?
Hint
Remember the notation isObjectName.PropertyName for line 7, with the object name of snoopy and the property name of species. Then useObjectName['PropertyName'] for line 10, with the property name age.


var snoopy = new Object();
snoopy.species = "beagle";
snoopy.age = 10;

// save Snoopy's age and species into variables
// use dot notation for snoopy's species
var species =snoopy['species'];
   
// use bracket notation for snoopy's age
var age = snoopy['age'];




Introduction to Objects I 30/33

What Are Objects For?
Objects provide us with a way to represent real-world or virtual things. We can do this by storing information inside the object's properties. There are two basic ways to make objects:
Literal Notation, where we use
var Name = { };
Constructor Notation, where we use the keyword new.
We've given an example in literal notation to refresh your memory.

Instructions
Make a new object, spencer2, with the same properties but using constructor notation and the Object constructor.
var spencer = {
  age: 22,
  country: "United States"
};
var spencer2 = new Object();
spencer2.age= 22;
spencer2.country= "United States";

Introduction to Objects I 29/33

Try it Out!
This time try making your own function that takes objects as parameters!
Here we have given you the Personconstructor again, along with theageDifference function as an example.
Now create a new function, olderAge. It should take two Person objects as parameters, and return the age of whatever Person is older. For example, with 30 year-old alice and 25 year-old bob, olderAge(alice, bob); should return 30, because that isalice's age and she is older than bob. If the two people have the same age then you can return that age.


Instructions
Define a function called olderAge. We want the function to return the age of the person who is older.
// Our person constructor
function Person (name, age) {
    this.name = name;
    this.age = age;
}
// We can make a function which takes persons as arguments
// This one computes the difference in ages between two people
var ageDifference = function(person1, person2) {
    return person1.age - person2.age;
};
// Make a new function, olderAge, to return the age of
// the older of two people
var olderAge = function(person1, person2) {
        if (person1.age > person2.age) {
        return person1.age;
    } else {
        return person2.age;
    }
};

// Let's bring back alice and billy to test our new function
var alice = new Person("Alice", 30);
var billy = new Person("Billy", 25);
console.log("The older person is " + olderAge(alice, billy));

Introduction to Objects I 28/33

Passing Objects into Functions
In addition to making arrays of Objects, we can use objects as parameters for functions as well. That way, these functions can take advantage of the methods and properties that a certain object type provides.
To see an example, take a look at the console. In addition to our Person constructor we have introduced a new function, ageDifference(line 9). This function takes two Personobjects as parameters, and returns the difference in age between the two people.
Notice we would be in trouble here if we tried to call ageDifference and passed in strings instead of people, because strings don't have an age property. But because we know from our constructor that all Person objects will have an age property, we can pass anyPerson into ageDifference. We must be careful not to pass anything but Personobjects into ageDifference.


Instructions
We have created two example people, aliceand billy. Complete line 17 by callingageDifference and saving the result in our global diff variable.
?
Hint
We can call ageDifference just as we might call any other function. And it will take two parameters, the names of our two objects.
                                                                       // Our person constructor
                                                                          function Person (name, age) {
                                                                          this.name = name;
                                                                          this.age = age;
                                                                            }

                                                                  // We can make a function which takes persons as arguments
                                                              // This one computes the difference in ages between two people
                                                                        var ageDifference = function(person1, person2) {
                                                                        return person1.age - person2.age;
                                                                          }

                                                                      var alice = new Person("Alice", 30);
                                                                      var billy = new Person("Billy", 25);

                                                            // get the difference in age between alice and billy using our function
                                                                var diff =  ageDifference(alice,billy);

Introduction to Objects I 27/33

Loop the loop
Arrays filled with objects will work just like arrays filled with numbers and strings.
In the same way we may loop through an array of numbers to print them out or calculate a sum, we can loop through an array of objects and access properties or methods.


Instructions
  1. Write a person constructor called Personthat has two properties (name and age).
  2. Create an empty array called family.
  3. There will be four objects in the array. Using your Person constructor, create the four objects and put them in the array. The order of the objects are:
    • "alice" who is 40
    • "bob" who is 42
    • "michelle" who is 8
    • "timmy" who is 6
  4. Create a for-loop that loops through thefamily array and prints out the nameproperty for each family member in order of creation.
?
Hint
If you need a quick brush-up on how for-loops work, review the exercises on loops.
Accessing the name property in the array and then using this in the for-loop is the trickiest part. Remember that we use dot notation to get the value of a property from an object:
objectName.propertyName;
And we can use the same dot notation to get the value of a property for one particular object in an array.
arrayName[2].propertyName;
This will get the third object in the array, and then find the value associated with the property.
Note that the objects must be in the order specified in the instructions!
                                                                       // Our person constructor
                                                                          function Person (name, age) {
                                                                          this.name = name;
                                                                          this.age = age;
                                                                           }

                                                                     // Now we can make an array of people
                                                                        var 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 old

                                                                     // Our Person constructor
                                                                        for(i=0;i<4;i++){console.log(family[i])};

                                                                     // loop through our new array






Introduction to Objects I 26/33

Arrays of Objects
Remember that an object is just another type, like a string or number but more complex. This means that just as we can make arrays of numbers and strings, we can also make arrays of objects.
Here we have our Person constructor which should look familiar. We can use this constructor to make an array of Personobjects, similar to how we might make an array of numbers but filling in people instead.


instructions
Add one more Person to the family array,"timmy", who is 6 years old.
// Our person constructor
function Person (name, age) {
    this.name = name;
    this.age = age;
}
// Now we can make an array of people
var 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 old

Introduction to Objects I 25/33

Constructors in Review
Constructors are a way to make objects with the keyword new. The most basic constructor is the Object constructor, which will make an object with no methods or properties.
For more complicated objects we can make our own constructors and put in whatever properties and methods we want.
Check out our example to the right to see objects in action. Our Rabbit constructor defines an adjective property and adescribeMyself method.
Recall how these kind of custom constructors are important because they allow us to easily make many similar objects.

Instructions
Create a new object rabbit1 with the adjective "fluffy", a new object rabbit2 with the adjective "happy", and a new objectrabbit3 with the adjective "sleepy".
Use the method describeMyself to print out in the console a sentence about each object you just created!
function Rabbit(adjective) {
    this.adjective = adjective;
    this.describeMyself = function() {
        console.log("I am a " + this.adjective + " rabbit");
    };
}
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");

Introduction to Objects I 24/33

Constructors With Methods
In addition to setting properties, constructors can also define methods. This way, as soon as the object is created it will have its own methods as well.
Here we have a Rectangle constructor, which sets the height and width properties equal to the arguments, just like our Person did with name and age.
Notice we have added a calcArea method. This calculates the area of the rectangle in terms of its height and width.
Line 11 creates a new object rex which makes use of the constructor. You can see how rex calls the calcArea method in line 12and saves the result in a variable, area.


Instructions
Define a new method on line 8,calcPerimeter, which calculates and returns the perimeter for a Rectangle in terms ofheight and width.
function Rectangle(height, width) {
  this.height = height;
  this.width = width;
  this.calcArea = function() {
      return this.height * this.width;
  };
  this.calcPerimeter = function() {
      return 2*this.height + 2*this.width
  };
}
var rex = new Rectangle(7,3);
var area = rex.calcArea();
var perimeter = rex.calcPerimeter();

Introduction to Objects I 23/33

More Options
In a constructor, we don't have to define all the properties using parameters. Look at our new Person example on line 1, and see how we set the species to be "Homo Sapiens" (line 4). This means that when we create anyPerson, their species will be "Homo Sapiens". In this way, the values associated with nameand age are not yet assigned, but specieswill always have the same value.
In this case, both sally and holden will have the same species of "Homo Sapiens", which makes sense because that is the same across all people.

Instructions
Create a new object called sally using the Person constructor. Her name is "Sally Bowles" and she is 39. Create another object called holden. His name is "Holden Caulfield" and he is 16.
Edit the sentence printed out such that it includes the age of sally and holdenrespectively.
?
Hint
Create the sally and holden objects with the Person constructor like we have been doing.
You can also make edits to the console.logstatements by using the + operator so you print their ages.
                                                               function Person(name,age,species) {
                                                               this.name = name;
                                                               this.age = age;
                                                               this.species = "Homo Sapiens";
                                                               }

                                                               var sally = new Person("Sally Bowles",39,"Homo Sapiens");
                                                               var holden = new Person("Holden Caulfield",16,"Homo Sapiens");
                                                               console.log("sally's species is " + sally.species + " and she is " + sally.age);
                                                               console.log("holden's species is " + holden.species + " and he is " + holden.age);