0

If I have a class:

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

  getArea() {
    return Rectangle.area(this.height, this.width);
  }

  static area(height, width) {
    return height * width;
  }
}

Then I can make an instance of that class and call my getArea function on the instance:

var x = new Rectangle(5,6);
console.log(x.getArea());

Now, say for some reason in my getArea function, instead of calling Rectangle.area directly, I wanted to find the class dynamically and call the static method on whatever dynamically the class instance is:

  getArea() {
    return this.class.area(this.height, this.width);
  }

In PHP, I can do that by something like static::area() or self::area(). How can I do something similar to static and self in Javascript to dynamically access static methods from the class that this belongs to?

TKoL
  • 13,158
  • 3
  • 39
  • 73
  • did you tried it with just `return this.area(this.height, this.width);` – bill.gates Aug 05 '20 at 12:22
  • @Ifaruki That ain't working… – deceze Aug 05 '20 at 12:30
  • you can create a property in constructor which refer to its __proto__ chain to access it. All static property or method stored in constructor property: create a property in constructor " this.self = this.__proto__.constructor" Now self variable has access of all the static method and property. getArea() { return this.self.area(this.height,this.width) } – deepak Aug 05 '20 at 12:32
  • 1
    @deepak Why all that bending over backwards when `this.constructor.area(..)` will do?! – deceze Aug 05 '20 at 12:35
  • @deceze - surely it will work , I just want to make clear how object store static data. – deepak Aug 05 '20 at 12:38

1 Answers1

1

You can refer to x.constructor.area(). When an instance is created, its constructor property will be made to refer to the constructor function. That's where static methods are found.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Thanks for your answer. I made [this jsfiddle](https://jsfiddle.net/gqcxLok7/) to test how `this.constructor` works when you extend a class. – TKoL Aug 05 '20 at 13:18