A better understanding: methods


#1

Why does a method have to be defined by a specific object and then called using the object again? What I mean is that the method is created with 'rectangle.setHeight' and then has to be called again with 'rectangle.setHeight(x)'. Is that not redundant? I would think that since the method is defined with the object originally that I should be able to simply call the method with 'setHeight(x)' or when it's being defined, completely removing 'rectangle' from the equation and only calling it with 'rectangle.setHeight'. Am I making any sense? Fee free to just tell me 'because that's how it works'.

Example is listed below


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);


#2

rectangle is an instance of Object class. However, Object does not have height, width attributes, and does not have, setHeight or setWidth methods.

When we define an object instance, we create in essence a new class of object once we begin assigning custom properties and methods. This will come up, so don't let it segue you just now.

The object is a sort of closure on its variables and methods. Only the rectangle instance may invoke its methods. It is the owner of those methods, exclusively. They cannot be called directly, and neither can any other object call it. Think of closure as being beneficial, and more will unfold as you progress through this and next unit.


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.