Pavel Gospodinov
Pavel Gospodinov

Reputation: 43

How to declare a class with constructor and child objects?

I want to create a class called Shapes that contains different shapes(objects), which has a constructor and then i want to add the different objects with their variables. At the end of all i want to display in the console the object's angles. So i wrote this code but something is missing..any ideas?

class Shapes {
  constructor(){
    var angles = 0;
  }
    Triangle(){
      angles = 3;
      return angles;
}
    Square(){
      angles = 4;
      return angles;
  }
  console.log(Triangle)
}

Upvotes: 0

Views: 44

Answers (2)

Ehsan
Ehsan

Reputation: 12959

This is another way :

function shapes(angle) {
  this.angles = angle;
}

var Triangle = new shapes(3);
var Square = new shapes(4);

console.log( Triangle.angles );
console.log( Square.angles );

Upvotes: 0

Ankit Agarwal
Ankit Agarwal

Reputation: 30739

You have completely misunderstood the class declaration and its usage. You first need to define a class with name Shapes so that the constructor will initialize the angles value. Then you can create different shapes(objects) with those angle values.

class Shapes {
  constructor(angles){
    this.angles = angles;
  }
}

var Triangle = new Shapes(3);
console.log(Triangle.angles);

var Square = new Shapes(4);
console.log(Square.angles);

Upvotes: 1

Related Questions