面试题答案
一键面试- 错误:在子类构造函数中调用
super()
之前使用this
会引发ReferenceError
,因为在调用super()
之前,this
并未被正确初始化。 - 避免错误及确保正确继承的方法:在子类构造函数中,首先调用
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;
}
}