gpt4 book ai didi

javascript - 控制台日志不从构造函数打印

转载 作者:行者123 更新时间:2023-12-02 22:47:27 25 4
gpt4 key购买 nike

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();

我希望控制台显示“这太棒了”和“我是你的父亲”。但在评论中间类的 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() {
// 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();

关于javascript - 控制台日志不从构造函数打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58334338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com