MST

星途 面试题库

面试题:JavaScript 中为现有类扩充静态方法并考虑继承性

有这样一个类继承结构: ```javascript class Shape { constructor(color) { this.color = color; } } class Rectangle extends Shape { constructor(color, width, height) { super(color); this.width = width; this.height = height; } } ``` 请为 `Shape` 类扩充一个静态方法 `getType`,这个方法返回字符串 `'Shape'`。同时确保 `Rectangle` 类及其实例能够正确访问这个静态方法,并且当 `Rectangle` 类调用 `getType` 方法时,返回 `'Rectangle'`。请解释你的实现思路及这样做的原理。
30.0万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
class Shape {
  constructor(color) {
    this.color = color;
  }
  static getType() {
    return 'Shape';
  }
}

class Rectangle extends Shape {
  constructor(color, width, height) {
    super(color);
    this.width = width;
    this.height = height;
  }
  static getType() {
    return 'Rectangle';
  }
}

实现思路

  1. Shape 类中直接定义静态方法 getType,返回字符串 'Shape'
  2. Rectangle 类中重写 getType 静态方法,返回字符串 'Rectangle'。这样 Rectangle 类及其实例在调用 getType 方法时,会调用自身重写的方法,返回 'Rectangle',而 Shape 类调用 getType 方法时,返回 'Shape'

原理

  1. 静态方法:静态方法属于类本身,而不属于类的实例。通过在类中使用 static 关键字定义静态方法,所有该类的实例都可以通过类名来访问这个静态方法。
  2. 方法重写:在继承体系中,子类可以重写从父类继承来的方法。当子类调用这个方法时,会优先调用子类自身重写的方法,而不是父类的方法。所以 Rectangle 类重写 getType 方法后,Rectangle 类及其实例调用 getType 方法会返回 'Rectangle',而 Shape 类调用 getType 方法会返回 'Shape'