class Circle {
constructor() {
this.width = 2;
this.height = 3;
}
static area() {
return this.width * this.height
}
}
console.log(Circle.area()) // NaN
我了解到 Class 的靜態方法將 this 系結到 Class 本身,而不是 Instance 的新物件。所以我希望 Cicle.area() 回傳 6,它來自 (2 * 3)。但實際結果回傳 NaN。我找不到原因。
uj5u.com熱心網友回復:
您的建構式系結到類的實體。這就是this.height和this.width存盤的地方(在類的實體上)。
靜態方法系結到類,類本身沒有靜態height或width屬性。因此,當您嘗試將兩個現有undefined值相乘時,您會得到 NaN 。
在這種情況下,如果你想area成為一個靜態方法,你必須將高度和寬度傳遞給它,因為它沒有系結到任何具有現有height或width.
class Rectangle {
static area(height, width) {
return width * height;
}
}
console.log(Rectangle.area(10, 6));
或者,如果要使用實體高度和寬度,則area需要是實體方法,而不是靜態方法。
class Rectangle {
constructor(height, width) {
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
let rect = new Rectangle(10, 6);
console.log(rect.area()) // 60
注意:我將示例轉換為 Rectangle 類,因為我不確定圓形的高度和寬度是什么意思。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/352338.html
標籤:javascript ecmascript-6 这个 静态方法
上一篇:獲取所選表格單元格的“資料”值
