企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
[TOC] # 基本概念 **`extends`** 关键字用于[类声明](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/class)或者[类表达式](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/class)中,以创建一个类,该类是另一个类的子类。 ## 语法 ~~~ class ChildClass extends ParentClass { ... } ~~~ ## 描述 `extends`关键字用来创建一个普通类或者内建对象的子类。 继承的`.prototype`必须是一个[`Object`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object "Object 构造函数创建一个对象包装器。")或者[`null`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/null "值 null 特指对象的值未设置。它是 JavaScript 基本类型 之一。")。 # 实践 ## 使用 `extends` 第一个例子是根据名为 `Polygon`类创建一个名为`Square`的类。 ~~~js class Square extends Polygon { constructor(length) { // Here, it calls the parent class' constructor with lengths // provided for the Polygon's width and height super(length, length); // Note: In derived classes, super() must be called before you // can use 'this'. Leaving this out will cause a reference error. this.name = 'Square'; } get area() { return this.height * this.width; } } ~~~ ## 使用 `extends`与内置对象 这个示例继承了内置的[`Date`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Date "此页面仍未被本地化, 期待您的翻译!")对象。 ~~~js class myDate extends Date { constructor() { super(); } getFormattedDate() { var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec']; return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear(); } } ~~~ ## 扩展 `null` 可以像扩展普通类一样扩展[`null`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/null "值 null 特指对象的值未设置。它是 JavaScript 基本类型 之一。"),但是新对象的原型将不会继承 [`Object.prototype`](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype "Object.prototype 属性表示 Object 的原型对象。")。 ~~~js class nullExtends extends null { constructor() {} } Object.getPrototypeOf(nullExtends); // Function.prototype Object.getPrototypeOf(nullExtends.prototype) // null new nullExtends(); //ReferenceError: this is not defined ~~~