3

I have the following classes

class Polygon {
   constructor(height, width) {
      this.height = height;
      this.width = width;
   }
}



class Square extends Polygon {
   constructor(sideLength) {
      super(sideLength, sideLength);
   }

   area() {
      return this.height * this.width;
   }

   sideLength(newLength) {
      this.height = newLength;
      this.width = newLength;
   }
}

and thei I create an instance of the class Square

var square = new Square(2);

My expectations were to find in the square object (directly in it and not in its prototype) the area and sideLength methods. Differently I find them in the __proto__ object. result

I don't understand why it happens. Could you "translate" this same code using a constructor rather than a class? Maybe I will more easily get the point in this way...

marco
  • 1,152
  • 1
  • 9
  • 20
  • 1
    That's one of the points of having classes - to have objects share a common single internal prototype object (here, `Square.prototype`, which is the same as `square.__proto__` or `Object.getPrototypeOf(square)`) - rather than every new object having its own methods – CertainPerformance Nov 26 '18 at 10:17
  • 2
    ES6 still uses prototype chaining, classes are just syntactically sugar. Edit: please read https://stackoverflow.com/questions/36419713/are-es6-classes-just-syntactic-sugar-for-the-prototypal-pattern-in-javascript for more information. – GuyT Nov 26 '18 at 10:37

1 Answers1

3

The method defined in the class are transformed as protoType method in order for all instances of the class to share the same method. A functional component version of your case would be

function Polygon(height, width) {
    this.height = height;
    this.width = width;
}


function Square(sideLength){
   Polygon.call(this, sideLength);
}

Square.prototype.area = function() {
   return this.height * this.width;
}

Square.prototype.sideLength(newLength) {
  this.height = newLength;
  this.width = newLength;
}

However if you define the function in the class constructor or using arrow functions they would belong to the class instance like

class Polygon {
   constructor(height, width) {
      this.height = height;
      this.width = width;
   }
}



class Square extends Polygon {
   constructor(sideLength) {
      super(sideLength, sideLength);
      this.getArea = function() {
         return this.height * this.width;
      }
      this.sideLengthWithBind = this.sideLength.bind(this);
   }

   area =() =>{
      return this.height * this.width;
   }

   sideLength(newLength) {
      this.height = newLength;
      this.width = newLength;
   }
}

const square = new Square(5);

console.log(square);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400