使用此访问静态函数

如果我有一个类:


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;

  }

}

然后我可以创建该类的实例并getArea在该实例上调用我的函数:


var x = new Rectangle(5,6);

console.log(x.getArea());

现在,由于某种原因,在我的getArea函数中Rectangle.area,我不想直接调用,而是想动态地找到类,并在类实例的任何动态上调用静态方法:


  getArea() {

    return this.class.area(this.height, this.width);

  }

static::area()在 PHP 中,我可以通过或之类的东西来做到这一点self::area()。我怎样才能做一些类似于Javascriptstatic的事情self来动态访问this所属类的静态方法?


富国沪深
浏览 91回答 1
1回答

Smart猫小萌

你可以参考x.constructor.area()。创建实例时,constructor将使其属性引用构造函数。这就是找到静态方法的地方。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript