【发布时间】: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 中执行类似于 static 和 self 的操作,以从 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