javascript中有三个具有继承性的类。当我在中产阶级中删除super()时,子构造函数不再打印console.log。但是,当我将super()放入中产阶级时,将显示所有3个控制台日志。想知道为什么丢失的中间super()甚至抵消了子控制台日志。
class Great {
constructor() {
console.log('this is great');
}
}
class Grand extends Great {
constructor() {
// super();
console.log('this is grand');
}
}
class Father extends Grand {
constructor() {
super();
console.log('I am your father');
}
}
function main() {
let dad = new Father();
}
main();
我希望控制台显示“这很盛大”和“我是你的父亲”。但是当评论中产阶级的上层人士时,唯一出现的是“这是伟大的”。
答案 0 :(得分:1)
class Great {
constructor() {
console.log('this is great');
}
}
class Grand extends Great {
constructor() {
// super();
console.log('this is grand');
}
}
class Father extends Grand {
constructor() {
// calls Grand constructor function and its console.log
super();
// ReferenceError: must call super constructor before using 'this' in derived class constructor
// The Grand constructor throws an error preventing the next line to be executed
console.log('I am your father');
}
}
function main() {
let dad = new Father();
}
main();
与以下相同:
const functionWithError = () => {
console.log('I am about to throw');
throw new Error('Throwing...');
}
const functionThatCallsFunctionWithError = () => {
functionWithError();
console.log('This console.log will never be called');
}
functionThatCallsFunctionWithError();
答案 1 :(得分:0)
在访问“ this”或从派生构造函数返回之前,必须在派生类中调用超级构造函数
class Great {
constructor() {
console.log('this is great');
}
}
class Grand extends Great {
constructor() {
super();
console.log('this is grand');
}
}
class Father extends Grand {
constructor() {
super();
console.log('I am your father');
}
}
function main() {
let dad = new Father();
}
main();