Can the method be applied to other Objects?


#1


Hi all,

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

https://www.codecademy.com/courses/spencer-sandbox/2/6?curriculum_id=506324b3a7dffd00020bf661#

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
rectangle.setWidth(8);
rectangle.setHeight(6);


#2

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.


#3

Awesome! Got it now! :smiley: