Social Icons

Pages

Thursday, December 1, 2016

Introduction to Objects I 18/33

Make Your Own Method
Let's look at a new example and get practice writing methods.
Here we have defined an object rectanglestarting on line 1. It has a two properties,height and width, which represents the height and width of the shape.
We have written a setHeight method which will update rectangle's height to the given parameter. This is very similar to setAge from our person example.
Note we have used the keyword this. thisis still a placeholder, but in this scenario, thiscan only ever refer to rectangle because we defined setHeight to be explicitly part ofrectangle by defining it asrectangle.setHeight.


Instructions
Finish the method setWidth. It should take a parameter newWidth. It will change the property width to the given parameter.
Then use the two methods setHeight andsetWidth to change rectangle's height to 6and width to 8.

var rectangle = new Object();
rectangle.height = 3;
rectangle.width = 4;
// here is our method to set the height
rectangle.setHeight = function (newHeight) {
  this.height = newHeight;
 };
// help by finishing this method
 rectangle.setWidth = function (newWidth) {
  this.width = newWidth;
 };
// here change the width to 8 and height to 6 using our new methods
rectangle.setHeight(6);
rectangle.setWidth(8);

No comments:

Post a Comment