MST

星途 面试题库

面试题:JavaScript 类继承构造函数的错误处理场景

假设你有一个父类 `Parent` 和一个子类 `Child`,子类通过 `extends` 关键字继承父类。在子类构造函数中调用 `super()` 之前使用 `this` 会引发什么错误?如何避免这个错误并且确保子类正确继承父类的属性和方法?请给出代码示例说明。
28.8万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
  1. 错误:在子类构造函数中调用 super() 之前使用 this 会引发 ReferenceError,因为在调用 super() 之前,this 并未被正确初始化。
  2. 避免错误及确保正确继承的方法:在子类构造函数中,首先调用 super(),然后再使用 this

以下是Java代码示例:

class Parent {
    private int value;
    public Parent(int value) {
        this.value = value;
    }
    public int getValue() {
        return value;
    }
}

class Child extends Parent {
    private String name;
    public Child(int value, String name) {
        super(value); // 先调用super()
        this.name = name;
    }
    public String getName() {
        return name;
    }
}

以下是Python代码示例(Python中通过super()调用父类构造函数,并且没有严格要求先调用super()再操作实例属性,但为了逻辑清晰和一致性,建议先调用super()):

class Parent:
    def __init__(self, value):
        self.value = value

    def get_value(self):
        return self.value


class Child(Parent):
    def __init__(self, value, name):
        super().__init__(value)  # 先调用super()
        self.name = name

    def get_name(self):
        return self.name

以下是JavaScript代码示例:

class Parent {
    constructor(value) {
        this.value = value;
    }
    getValue() {
        return this.value;
    }
}

class Child extends Parent {
    constructor(value, name) {
        super(value); // 先调用super()
        this.name = name;
    }
    getName() {
        return this.name;
    }
}