JavaScript 中 class 语法继承构造函数参数怎么传
在 javascript 的 class 继承中,子类构造函数的参数传递必须通过 super() 调用显式传递给父类。核心规则是:子类必须先调用 super() 才能访问 this,且 super() 的参数直接对应父类构造函数的形参。若父类构造函数需要特定参数,子类必须在 super() 中提供;若父类无参或参数可选,可省略或传默认值。

子类如何定义并调用 super 传递参数
子类通过 constructor(...args) 接收参数,并在函数体首行使用 super(...args) 将参数透传给父类。例如,父类 Animal 需要 name 和 age,子类 Dog 可定义自己的参数(如 breed),并将 name 和 age 作为 super() 的参数传入。这样父类初始化完成后,子类再设置自身属性。

class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
class Dog extends Animal {
constructor(name, age, breed) {
super(name, age); // 传递 name 和 age 给父类
this.breed = breed; // 子类特有属性
}
}
const dog = new Dog('Buddy', 3, 'Golden Retriever');
console.log(dog.name); // "Buddy"
console.log(dog.breed); // "Golden Retriever"子类如何处理父类参数缺失或默认值
当父类构造函数有默认参数时,子类可通过解构或条件判断灵活传递。若子类未提供某些参数,可使用默认值调用 super()。例如,父类 Shape 接受 x 和 y,子类 Circle 可仅传 r,并在 super() 中使用默认坐标 (0, 0)。这确保父类始终获得有效参数,避免 undefined 错误。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。
立即学习“Java免费学习笔记(深入)”;

class Shape {
constructor(x = 0, y = 0) {
this.x = x;
this.y = y;
}
}
class Circle extends Shape {
constructor(r) {
super(0, 0); // 使用默认值传递 x 和 y
this.r = r;
}
}
const circle = new Circle(5);
console.log(circle.x); // 0
console.log(circle.y); // 0
console.log(circle.r); // 5基于 super() 调用顺序的具体问题
在子类构造函数中,super() 必须在访问 this 之前调用。若先使用 this 后调用 super(),会抛出 ReferenceError。这是因为 this 在 super() 执行前未初始化。例如,以下代码会报错:this.prop = 1; super();。正确做法是先 super() 再赋值 this。验证输入:子类构造函数中 this 的使用顺序直接影响程序是否崩溃。

















