helpME1986
helpME1986

Reputation: 1013

Constructor Function vs Factory Function in regards of creating a getter

I have tried to create getters using both approaches - factory function

function CreateCircle(radius) {
  return {
    radius,
    get area() {
        return this.radius * 20;
    }
   }
}

- and constructor function

  function ConstructorFunctionCircle(radius) {
      this.radius = radius;
      this.area = () => this.radius * 20;
  }

Then I created objects I log the area in a console:

  const constructorFunctionCircle = new ConstructorFunctionCircle(20);
  const factoryFunctionCircle = CreateCircle(20);

  console.log(`factoryFunctionCircle ${factoryFunctionCircle.area}`);
  console.log(`constructorFunctionCircle ${constructorFunctionCircle.area}`);

The result is:

   factoryFunctionCircle  400
   constructorFunctionCircle () => this.radius * 20

So, I understand that in case of a constructor function, I should invoke a method using ().

How then can I create a getter property using constructor function ?

Upvotes: 0

Views: 693

Answers (2)

Tim Klein
Tim Klein

Reputation: 2758

You could define another function (lambda in this case) like so:

this.calculateArea = () => this.radius * 20;

And then have your original property simply call that function:

this.area = this.calculateArea();

But a class would definitely be the preferable option.

Upvotes: 1

Jonas Wilms
Jonas Wilms

Reputation: 138257

With a real constructor function you have to use defineProperty:

  function ConstructorFunctionCircle(radius) {
    this.radius = radius;
    Object.defineProperty(this, "area", {
      get: function() {
        return radius * 20;
      }
    });
 }

However I would prefer a class instead:

  class Circle {
    constructor(radius) {
       this.radius = radius;
    }
    get area() {
      return 2 * Math.PI * this.radius ** 2;
    }
 }

Upvotes: 2

Related Questions