Social Icons

Pages

Thursday, December 1, 2016

Introduction to Objects I 15/33

So What's a Method?
In the last section, we discussed properties. We can think of properties as variables associated with an object. Similarly, a methodis just like a function associated with an object.
Let's look at bob, our same person object from the last lesson. Instead of just having the properties name and age (line 3 & 4), bobalso has a method called setAge (line 6). As you can probably guess, this method setsbob's age to whatever argument you give it.
Notice how we define setAge kind of like we define a property. The big difference is that we put in a function after the equals sign instead of a string or number.
We call a method like a function, but we useObjectName.methodName(). Look at line 10where we use the method to change bob's age to 40. We did this by callingbob.setAge(40);.


Instructions
Try it yourself! Use the method setAge to setbob's age to 20.
// here is bob again, with his usual properties
var bob = new Object();
bob.name = "Bob Smith";
bob.age = 30;
// this time we have added a method, setAge
bob.setAge = function (newAge){
  bob.age = newAge;
};
// here we set bob's age to 40
bob.setAge(20);
// bob's feeling old.  Use our method to set bob's age to 20

No comments:

Post a Comment