【问题标题】:access static functions with this [duplicate]用这个访问静态函数[重复]
【发布时间】:2020-11-25 14:42:52
【问题描述】:

如果我有课:

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);
  }

在 PHP 中,我可以通过 static::area()self::area() 之类的方式做到这一点。如何在 Javascript 中执行类似于 staticself 的操作,以从 this 所属的类中动态访问静态方法?

【问题讨论】:

  • 你用return this.area(this.height, this.width);试过了吗
  • @Ifaruki 那行不通……
  • 你可以在构造函数中创建一个属性来引用它的 proto 链来访问它。存储在构造函数属性中的所有静态属性或方法:在构造函数“this.self = this.__proto__.constructor”中创建一个属性现在self变量可以访问所有静态方法和属性。 getArea() { return this.self.area(this.height,this.width) }
  • @deepak 为什么当this.constructor.area(..) 可以做到时,所有向后弯腰?!
  • @deceze - 它肯定会起作用,我只是想弄清楚对象如何存储静态数据。

标签: javascript class


【解决方案1】:

您可以参考x.constructor.area()。当一个实例被创建时,它的constructor 属性将被用来引用构造函数。这就是找到静态方法的地方。

【讨论】:

  • 感谢您的回答。我创建了this jsfiddle 来测试扩展类时this.constructor 的工作原理。
猜你喜欢
  • 2013-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-12
相关资源
最近更新 更多