HarmonyOS鸿蒙Next中为什么子类中用super.schoolname会打印undefined,用this.schoolname就没事
HarmonyOS鸿蒙Next中为什么子类中用super.schoolname会打印undefined,用this.schoolname就没事
这是我的代码:
class Inschool {
protected id:string
name:string
gender:string
protected schoolname:string
constructor(id:string,name:string,gender:string){
this.id=id
this.name=name
this.gender=gender
this.schoolname = '大学'
}
protected sayHi(){
console.log(`大家好,我叫${this.name}`)
}
}
class Student extends Inschool{
t_or_s:String = '学生'
constructor(id:string,name:string,gender:string) {
super(id,name,gender)
}
sayHi(): void {
console.log(`大家好,我叫${this.name},学号${this.id},是${this.schoolname}的一名${this.t_or_s}`)
}
}
let xiaoming:Student = new Student('001','小明','男')
xiaoming.sayHi()
console.log(大家好,我叫${this.name},学号${this.id},是${this.schoolname}的一名${this.t_or_s})这句代码在打印台显示
但是将this.schoolname改成super.schoolname之后,打印台输出undefined
请问这是为什么呢
更多关于HarmonyOS鸿蒙Next中为什么子类中用super.schoolname会打印undefined,用this.schoolname就没事的实战教程也可以访问 https://www.itying.com/category-93-b0.html
这个是TS语言特性,可以看一下这个链接Class 的继承 - ECMAScript 6入门 (ruanyifeng.com)
父类定义的class字段在子类中不能通过super访问。
TS语言特性,ArkTS围绕应用开发在TS 生态基础上做了进一步扩展,保持了TS的基本风格,所以ArkTS也不支持此写法
更多关于HarmonyOS鸿蒙Next中为什么子类中用super.schoolname会打印undefined,用this.schoolname就没事的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,super.schoolname打印undefined而this.schoolname正常,通常是因为super关键字用于访问父类的属性和方法,而this关键字用于访问当前实例的属性和方法。如果父类中没有定义schoolname属性,或者该属性未在构造函数中初始化,super.schoolname将返回undefined。而this.schoolname访问的是当前实例的属性,如果该属性已在当前类或实例中定义并赋值,this.schoolname将返回正确的值。
在HarmonyOS鸿蒙Next中,super.schoolname打印undefined是因为super关键字用于访问父类的属性和方法,而schoolname可能并未在父类中定义。this.schoolname则访问当前实例的属性,如果当前实例有schoolname属性,就能正确打印。建议检查父类是否定义了schoolname,或确保在子类中正确初始化了该属性。

