在 javascript 类中,同名的实例字段(如 `method = "sss"`

JavaScript 类中,字段声明(Class Fields) 与 方法定义(Method Definitions) 虽然语法相似、名称相同,但底层机制截然不同,直接决定了属性查找时的行为差异。
✅ method = "sss" 是 公共类字段(Public Class Field),等价于在 constructor() 中执行 this.method = "sss"。
→ 它会在每次实例化时(即 new Child())为该实例创建一个自有属性(own property),存在于实例对象自身上。
✅ method() { ... } 是 原型方法(Prototype Method),会被定义在 Child.prototype 或 Parent.prototype 上,不占用实例内存,所有实例共享该函数引用。
可通过 hasOwnProperty() 清晰验证:
class Parent {
method = "sss";
parentMethod() { console.log("Parent"); }
}
class Child extends Parent {
method() { console.log("Child"); }
}
const child = new Child();
console.log(child.hasOwnProperty("method")); // true ← 字段优先存在实例上
console.log(child.hasOwnProperty("parentMethod")); // false ← 方法在原型上
console.log(Child.prototype.hasOwnProperty("method")); // false
console.log(Child.prototype.hasOwnProperty("parentMethod")); // false
console.log(Parent.prototype.hasOwnProperty("parentMethod")); // true当 child.method 被读取时,JavaScript 引擎按 属性访问规则 查找:
因此,即使 Child 类定义了同名方法 method() {},它也仅存在于 Child.prototype.method,而 child.method 仍指向实例上的字符串 "sss" —— 这不是“覆盖失败”,而是字段与方法根本不在同一查找层级。
? 类比理解:child.method 就像 child["method"],访问的是数据属性;而 child.method() 的调用之所以报错("sss" is not a function),正是因为取到的是字符串而非函数。
class Parent {
method() { console.log("Parent"); }
}
class Child extends Parent {
method() { console.log("Child"); } // ✅ 正确覆盖:子类方法在原型链更高层
}| 特性 | method = "sss"(类字段) | method() {}(类方法) |
|---|---|---|
| 存储位置 | 实例对象自身(child.method) | 原型对象(Child.prototype.method) |
| 初始化时机 | 每次 new 时执行赋值 | 类定义时一次性绑定到原型 |
| 可枚举性 | true(默认) | false(方法不可枚举) |
| 优先级(访问时) | 始终高于原型上的同名属性 | 被实例字段遮蔽后不可见 |
掌握这一机制,是写出可维护、可预测的 JavaScript 类的关键基础。更多细节可参考 MDN:Public class fields。