Aravinda KS
Aravinda KS

Reputation: 195

How to add an method outside to class in ES6 JS

My class is

class calculate {
    constructor(l,b) {
        this.l = l;
        this.b = b;
    }
}

I need to add a method called area to the above class, is there any way I can add? I tried looking for documentation but i didn't find the correct answer. I would really appreciate if anyone helped me in this.

Upvotes: 0

Views: 1958

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371138

A class is mostly just syntax sugar for a constructor function and assignments to its prototype. This, for example:

class calculate {
   constructor(l, b) {
      this.l = l;
      this.b = b;
   }
   someMethod() {
      
   }
}

is mostly equivalent to

function calculate(l, b) {
   this.l = l;
   this.b = b;
}
calculate.prototype.someMethod = function () {

};

You can assign to the .prototype of classes the same way:

class calculate {
   constructor(l,b) {
       this.l = l;
       this.b = b;
   }
}
calculate.prototype.area = function() {
   // ...
};

(but this is pretty strange to do - this would usually be indicative of smelly code. Consider if you can rework the requirements so that the class constructor and its methods can be defined all at once instead.)

Upvotes: 2

Related Questions