Jahttps://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909aScript class中不能用计算属性名定义实例或静态字段,但支持在方法、getter/setter及constructor中使用计算名;方法和访问器需用方括号包裹表达式,constructor中可通过this[key]动态添加属性。

Jahttps://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909aScript class 中不能直接用计算属性名定义实例属性(即类字段),但可以用计算属性名定义方法和 getter/setter,也能在 constructor 中动态添加带计算名的属性。
计算属性名定义方法
在 class 的方法定义中,可以用方括号 [] 包裹表达式,实现动态方法名:
const methodName = 'sayHello';
<p>class Greeter {
[methodName]() {
return 'Hello!';
}
}</p><p>const g = new Greeter();
console.log(g.sayHello()); // 'Hello!'
// 注意:g[methodName]() 效果相同
计算属性名定义 getter / setter
getter 和 setter 同样支持计算名,写法一致:
- 必须成对出现(若只定义一个,另一个会是 undefined)
- 计算名需为字符串或可转字符串的值
const propName = 'https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909alue';
<p>class Box {
constructor(https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909al) {
this._https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909al = https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909al;
}
get [propName]() {
return this._https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909al;
}
set <a href="https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909">propName</a> {
this._https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909al = https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909;
}
}</p><p>const b = new Box(42);
console.log(b.https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909alue); // 42
b.https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909alue = 100;
console.log(b.https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909alue); // 100
constructor 中动态添加计算名实例属性
class 声明体不支持类似 [key] = https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909alue 的字段语法(ES2022 起的公共类字段仍不支持计算名),但可在 constructor 内通过方括号赋值实现:
立即学习“Java免费学习笔记(深入)”;
class User {
constructor(name) {
const key = `fullName`;
this[key] = name;
}
}
<p>const u = new User('Alice');
console.log(u.fullName); // 'Alice'
console.log(u['fullName']); // 'Alice'
注意点与限制
以下写法不合法,会报语法错误:
-
class C { [expr] = 123; }—— 类字段不支持计算名 -
class C { static [expr] = 456; }—— 静态字段同样不支持(截至 ES2024) -
[expr]() {}出现在类外或非 class 方法上下文中无效
如需静态成员的动态名,只能在 class 外赋值:C[computedKey] = https://www.php.cn/link/27464bb328aa347a2dc55a9f1bafa909alue;


















