18 make your own method


#1

18 make your own method in intro to objects 1

Why does this code work? I thought i needed to put in
rectangle.setHeight = setHeight;
rectangle.setHeight(6);
rectangle.setWidth = setWidth;
rectangle.setWidth(8);

but it doesn't accept it

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);
console.log(rectangle)


#2

Methods setWidth() and setHeight() assigning new value for width and height properties. So you can't and don't need to do rectangle.setHeight = setHeight;. All you need it's just to call method and put new value as an argument.

Why does this code work?
Actually, it doesn't work because setHeight (right part) is not defined.


#3

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