javascript 中通过 extends 关键字让自定义类继承内置类,并在构造函数中调用 super() 初始化父类状态。以 array 为例,子类必须显式调用 super() 并正确传递参数,否则无法获得内置类的内部槽位(如 length)。

如何继承 Array 并实现 push 方法
直接回答:使用 class MyArray extends Array {} 语法,在 constructor 中调用 super(...args) 即可继承数组行为。push 方法会自动复用内置逻辑,无需重写。

class MyArray extends Array {
constructor(...args) {
super(...args);
}
}
const arr = new MyArray(1, 2, 3);
console.log(arr.length); // 3
arr.push(4);
console.log(arr.length); // 4
console.log(arr instanceof MyArray); // true
console.log(arr instanceof Array); // true
预期结果:length 初始为 3,push 后变为 4,instanceof 检查均返回 true。这证明子类正确继承了内置类的内部状态和方法。
为什么需要手动处理 this 绑定
直接回答:虽然 extends 自动设置原型链,但某些内置方法依赖 this 指向实例。若手动创建对象或修改原型,需确保 this 正确绑定到子类实例。
一个基于源码的 OpenAI Agents SDK JavaScript 和 TypeScript 技术文档。涵盖了代理编排、工具、转接、追踪以及实际安装路径。

class SafeArray extends Array {
constructor(...args) {
super(...args);
// 确保 this 是 SafeArray 实例
Object.setPrototypeOf(this, SafeArray.prototype);
}
safePush(item) {
if (typeof item !== 'number') {
throw new TypeError('Only numbers allowed');
}
return this.push(item);
}
}
const arr = new SafeArray();
arr.safePush(1);
console.log(arr.length); // 1
try {
arr.safePush('a');
} catch (e) {
console.log(e.message); // Only numbers allowed
}
预期结果:safePush 成功添加数字,长度增加;尝试添加字符串时抛出 TypeError。Object.setPrototypeOf 确保 this 始终指向 SafeArray 实例,避免方法调用时上下文丢失。
继承内置类时如何处理空值输入
直接回答:当传入 undefined 或 null 作为构造参数时,super() 会将其视为普通值处理,不会触发错误。例如 new Array(undefined) 创建长度为 1 的稀疏数组,而非报错。
class NullSafeArray extends Array {
constructor(...args) {
// 过滤掉 undefined 和 null
const validArgs = args.filter(arg => arg !== undefined && arg !== null);
super(...validArgs);
}
}
const arr1 = new NullSafeArray(1, undefined, 2, null, 3);
console.log(arr1.length); // 3
console.log(arr1[0]); // 1
console.log(arr1[1]); // 2
console.log(arr1[2]); // 3
const arr2 = new NullSafeArray();
console.log(arr2.length); // 0
console.log(Array.isArray(arr2)); // true
预期结果:arr1 长度为 3,仅包含有效值;arr2 为空数组。filter 操作在 super() 前执行,确保内置类只接收合法参数,避免意外创建稀疏数组或未定义元素。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










