Can the method be applied to other Objects?


Hi all,

my name is Bart, and I was working on this exercise:

The code below should do it for this exercise.

I was just wondering, if the method .setWidth and .setHeight could be used in this case to change the width and height of other Objects. Is this the case, even when the function was created within the object rectangle?

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


If we write the function as a global method (it will be in the context of the window object) and retain the this variable,

var setHeight = function (newHeight) {
    this.height = newHeight;

we can then assign the method to any object.

rectangle.setHeight = setHeight;

var triangle = {};
triangle.setHeight = setHeight;

Now both objects have a copy of the method in their own context.

There is a more advanced approach which you will soon begin to learn, custom constructors, but let's not get ahead of ourselves.


Awesome! Got it now! :smiley: