为什么在超类中定义时,在子类中使用超级(资格)会引发ReferenceError?

问题描述:

为什么在超类中定义时,在子类中使用超级(资格)会引发ReferenceError?

class SchoolEmployee { 
 
    constructor(name, qualifications) { 
 
    this._name = name; 
 
    this._qualifications = qualifications; 
 
    this._holidaysLeft = 21; 
 
    } 
 

 
    get name() { 
 
    return this._name; 
 
    } 
 

 
    get qualifications() { 
 
    return this._qualifications; 
 
    } 
 

 
    get holidaysLeft() { 
 
    return this._holidaysLeft; 
 
    } 
 

 
    takeHolidays(days) { 
 
    this._holidaysLeft -= days; 
 
    } 
 
} 
 

 
class Teacher extends SchoolEmployee { 
 
    constructor(name, qualifications, subject) { 
 
    super(name); 
 
    super(qualifications); //THIS IS THE ERROR 
 
    this._subject = subject; 
 
    } 
 

 
    get name() { 
 
    return this._name; 
 
    } 
 

 
    get qualifications() { 
 
    return this._qualifications; 
 
    } 
 

 
    get subject() { 
 
    return this._subject; 
 
    } 
 
} 
 

 
let John = new Teacher('John', ['Maths', 'Physics'], 'Maths');

SchoolEmployee是超一流的,我已经定义了什么 '资格' 的。据我所知,写超级(资格)调用超级类的构造函数,它是先前定义的。目前我正在学习Javascript,并且我不明白哪里出了问题。有谁能够帮助我?

+0

什么是确切的错误信息? – Quentin

+0

'ReferenceError:未在新教师处(D:\ MAIN \ COding \ javascript \ classes.js:28:5) 处于Object处定义 。在Module._compile(module.js:570:32) (Object.Module._extensions..js(module.js:579: 10) at Module.load(module.js:487:32) at try.ModuleLoad(module.js:446:12) at Function.Module._load(module.js:438:3) at Module.runMain(module.js: (bootstrap_node.js:389:7) 在启动时(bootstrap_node.js:149:9) – hu1k909

正如你可以查看on mdn super()调用父类的构造函数,并且你调用它两次。你可能想要的是

class Teacher extends SchoolEmployee { 
    constructor(name, qualifications, subject) { 
     super(name, qualifications); 
     this._subject = subject; 
    } 
} 

SchoolEmployee构造函数需要调用两个参数,只有一个参数超。请尝试:

super(name, qualifications); 

错误清楚地说明了Super constructor may only be called onceSuper调用构造函数,并且父构造函数接受name, qualifications将它们传递给一个super

class SchoolEmployee { 
 
    constructor (name, qualifications) { 
 
    this._name = name; 
 
    this._qualifications = qualifications; 
 
    this._holidaysLeft = 21; 
 
    } 
 

 
    get name() { 
 
    return this._name; 
 
    } 
 

 
    get qualifications() { 
 
    return this._qualifications; 
 
    } 
 

 
    get holidaysLeft() { 
 
    return this._holidaysLeft; 
 
    } 
 

 
    takeHolidays(days) { 
 
    this._holidaysLeft -= days; 
 
    } 
 
} 
 

 
class Teacher extends SchoolEmployee { 
 
    constructor (name, qualifications, subject) { 
 
    super(name, qualifications); 
 
    this._subject = subject; 
 
    } 
 

 
    get name() { 
 
    return this._name; 
 
    } 
 

 
    get qualifications() { 
 
    return this._qualifications; 
 
    } 
 

 
    get subject() { 
 
    return this._subject; 
 
    } 
 
} 
 

 
let John = new Teacher('John',['Maths', 'Physics'],'Maths');