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?

5
  • did you tried it with just return this.area(this.height, this.width); Commented Aug 5, 2020 at 12:22
  • @Ifaruki That ain't working… Commented Aug 5, 2020 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) } Commented Aug 5, 2020 at 12:32
  • 1
    @deepak Why all that bending over backwards when this.constructor.area(..) will do?! Commented Aug 5, 2020 at 12:35
  • @deceze - surely it will work , I just want to make clear how object store static data. Commented Aug 5, 2020 at 12:38

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer. I made this jsfiddle to test how this.constructor works when you extend a class.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.