console.log(Shape.color); // blue
console.log(Shape.getColor()); // blue
console.log(‘color’ in Shape); // true
console.log(‘getColor’ in Shape); // true
console.log(‘getMessage’ in Shape); // false
实例不能访问静态字段和方法:
const shapeInstance = new Shape();
console.log(shapeInstance.color); // undefined
console.log(shapeInstance.getColor); // undefined
console.log(shapeInstance.getMessage());// color:undefined
静态字段只能通过静态方法访问:
console.log(Shape.getColor()); // blue
console.log(Shape.getMessage()); //TypeError: Shape.getMessage is not a function
这里的 Shape.getMessage() 就报错了,这是因为 getMessage 不是一个静态函数,所以它不能通过类名 Shape 访问。可以通过以下方式来解决这个问题:
getMessage() {
return color:${Shape.color}
;
}
静态字段和方法是从父类继承的:
class Rectangle extends Shape { }
console.log(Rectangle.color); // blue
console.log(Rectangle.getColor()); // blue
console.log(‘color’ in Rectangle); // true
console.log(‘getColor’ in Rectangle); // true
console.log(‘getMessage’ in Rectangle); // false
4. 静态私有字段和方法
与私有实例字段和方法一样,静态私有字段和方法也使用哈希 (#) 前缀来定义:
class Shape {
static #color = ‘blue’;
static #getColor() {
return this.#color;
}
getMessage() {
return color:${Shape.#getColor()}
;
}
}
const shapeInstance = new Shape();
shapeInstance.getMessage(); // color:blue
私有静态字段有一个限制:只有定义私有静态字段的类才能访问该字段。这可能在我们使用 this 时导致出乎意料的情况:
class Shape {
static #color = ‘blue’;
static #getColor() {
return this.#color;
}
static getMessage() {
return color:${this.#color}
;
}
getMessageNonStatic() {
return color:${this.#getColor()}
;
}
}
class Rectangle extends Shape {}
console.log(Rectangle.getMessage()); // Uncaught TypeError: Cannot read private member #color from an object whose class did not declare it
const rectangle = new Rectangle();
console.log(rectangle.getMessageNonStatic()); // TypeError: Cannot read private member #getColor from an object whose class did not declare it
在这个例子中,this 指向的是 Rectangle 类,它无权访问私有字段 #color。当我们尝试调用 Rectangle.getMessage() 时,它无法读取 #color 并抛出了 TypeError。可以这样来进行修改:
class Shape {
static #color = ‘blue’;
static #getColor() {
return this.#color;
}
static getMessage() {
return ${Shape.#color}
;
}
getMessageNonStatic() {
return color:${Shape.#getColor()} color
;
}
}
class Rectangle extends Shape {}
console.log(Rectangle.getMessage()); // color:blue
const rectangle = new Rectangle();