先上正确版本
-
父类Person.ts
class Person { name:string age:number constructor(name:string,age:number) { this.name = name this.age = age } } export {Person}
-
子类Student.ts
import Action from "../interfaces/Action"; import {Person} from "./Person"; import Sex from "../enums/Sex"; /*子类Student,继承父类Person*/ class Student extends Person implements Action{ readonly sex:Sex constructor(name:string,age:number,sex:Sex) { super(name,age); this.sex = sex } behavior(): void { console.log(`${this.name} ${this.age} ${this.sex.valueOf()}`) } } export default Student
再说说错误例子
-
父类Person.ts
class Person { name:string age:number } export {Person}
-
子类Student.ts
import Action from "../interfaces/Action"; import {Person} from "./Person"; import Sex from "../enums/Sex"; /*子类Student,继承父类Person*/ class Student extends Person implements Action{ readonly sex:Sex constructor(name:string,age:number,sex:Sex) { super(); this.name = name this.age = age this.sex = sex } behavior(): void { console.log(`${this.name} ${this.age} ${this.sex.valueOf()}`) } } export default Student
有人可能反驳我说,父类中没有定义无参数的constructor
,但是我想说,定义了也不好使!请看下面代码,依然是报错不行的!
-
父类Person.ts
class Person { name:string age:number constructor() {} } export {Person}
-
子类Student.ts
import Action from "../interfaces/Action"; import {Person} from "./Person"; import Sex from "../enums/Sex"; /*子类Student,继承父类Person*/ class Student extends Person implements Action{ readonly sex:Sex constructor(name:string,age:number,sex:Sex) { super(); this.name = name this.age = age this.sex = sex } behavior(): void { console.log(`${this.name} ${this.age} ${this.sex.valueOf()}`) } } export default Student
所以我得出结论,初始化类实体时,在constructor中仅能对定义在该类的属性初始化
其实,想要在constructor对父类中的属性初始化,也可以用另一种方式——用接口继承类(Java转来的朋友,不要疑惑,Ts是支持接口继承类的),然后用类实现接口,看下面例子
-
父类Person
class Person { name:string age:number constructor() {} } export {Person}
-
接口Action.ts
import {Person} from "../pojo/Person"; interface Action extends Person{ behavior():void } export default Action
-
子类Student.ts
import Action from "../interfaces/Action"; import Sex from "../enums/Sex"; class Student implements Action{ age: number; name: string; readonly sex:Sex constructor(name:string,age:number,sex:Sex) { this.name = name this.age = age this.sex = sex } behavior(): void { console.log(`${this.name} ${this.age} ${this.sex.valueOf()}`) } } export default Student