16 - Method/Function specific to one object. Why is 'this.' needed?


#1

So heres the correct code according to this lesson within 'Introduction to Objects 1 - 16: Make Your Own Method'

//Establishing the Object
var rectangle = new Object(); 

//Setting its properties
rectangle.height = 3;
rectangle.width = 4;

//Creating Methods/Functions SPECIFIC to the object 'rectangle'.
rectangle.setHeight = function (newHeight) {
  this.height = newHeight;
};

rectangle.setWidth = function (newWidth) {
  this.width = newWidth;
};

//Calling on setHight, and setWidth, easily changing rectangle's properties
rectangle.setHeight(6);
rectangle.setWidth(8);

I am having a little trouble getting my head wrapped around the 'this.' here. Now in the previous task/lesson/exercise we established the method FIRST, and the 'this.' was placed inside the function to represent the object using it. That made sense to me because 'this.' serves as the 'X' in the function - where any object can take its place.

BUT in this case, we are assigning the function to rectangle and rectangle only (Or at least thats how I see it. If this is the case - why cant we just code it like so:

//Creating Methods/Functions SPECIFIC to the object 'rectangle'.

rectangle.setHeight = function (newHeight) {
  height = newHeight;  //taking OUT 'this.'
};

rectangle.setWidth = function (newWidth) {
  width = newWidth;  //taking OUT 'this.'
};

Why do we need 'this.'? Can someone help get my head wrapped around the logic behind the 'this.'?!

Thanks in advance


#2

Because you're setting the height and width of the OBJECT that is using the function (rectangle), so when you use 'this.' it's setting the rectangle height and weight in the OBJECT to have that value. You cannot affect these values otherwise. because just saying height or width, would be seen as a class/global variable and not an object specific variable.

If that doesn't make sense I can try to explain how it's useful to have this in a program, however I believe this describes you dilemma.