19. Help on "More Kinds Of Methods"



The code works but I'm having trouble grasping the keyword 'this' concept. On this exercise why use this.sideLength? We're inside of the square object and we're doing the method for the square object. Why not just use square.sideLength?

var square = new Object();
square.sideLength = 6;
square.calcPerimeter = function() {
  return this.sideLength * 4;
// help us define an area method here
square.calcArea = function() {
    return this.sideLength * this.sideLength;

var p = square.calcPerimeter();
var a = square.calcArea();


I'm guessing it's just simpler to use "square" than "this" seen as it might be easier for the coder to differentiate two objects. I suggest you do some experimenting on your own and see what works and see what doesn't. Different coders have different coding preferences. Hope I helped in some way.


this keyword in object's method as in this case will always reference to the current object, imagine that you have like 1000 different methods and in every method you still use hardcoded object's name you will need to change that name in every method to make it work if you decide to change variable name later in the future. Of course, these days it becomes less of a problem because using text editors or IDEs you can change particular word easily.


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