You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript类中同名方法与变量表现差异的原因探究

JavaScript类继承中实例属性与原型方法的优先级问题

示例1:符合预期的方法覆盖

class Parent{
    method(){
        console.log("Parent");
    }
}
class Child extends Parent{
    method(){
        console.log("Parent");
    }
}
var child = new Child();
console.log(child.method);

控制台返回Child类中的method方法,这是符合预期的行为。

示例2:出现疑问的属性优先级问题

class Parent{
    method = "sss"
}
class Child extends Parent{
    method(){
        console.log("Child")
    }
}
var child = new Child();
console.log(child.method)

原因解析

核心在于实例自身属性的优先级高于原型链上的方法:

  • 父类里的method = "sss"是类字段声明,这类属性会直接被添加到每个实例的自身属性上——包括子类实例,因为子类继承了父类的实例初始化逻辑。
  • 子类里的method()是原型方法,它被挂载到Child.prototype上,属于原型链层级的属性。
  • 当访问child.method时,JS会先从实例自身的属性列表里查找,找到父类定义的method(值为"sss")后就停止查找,不会再去原型链上找子类的方法。

而第一个示例里,父类和子类的method都是原型方法,子类的原型方法会覆盖父类的同名原型方法,所以访问时返回子类的方法。

内容的提问来源于stack exchange,提问作者MOHAMED SIKKANDAR AFZAL M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 05:16:16