javascript中有三个具有继承性的类。 当我删除中产阶级中的 super(( 时,子构造函数不再打印控制台.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();
我希望控制台显示"这很宏伟"和"我是你的父亲"。 但唯一出现的是"这很宏伟",在评论中产阶级的超级时。
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();
取消注释 class Grand 中的超级
在访问"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();