gpt4 book ai didi

inheritance - 你如何访问 Typescript 中基类的属性?

转载 作者:搜寻专家 更新时间:2023-10-30 20:31:35 25 4
gpt4 key购买 nike

有人建议使用这样的代码

class A {
// Setting this to private will cause class B to have a compile error
public x: string = 'a';
}

class B extends A {
constructor(){super();}
method():string {
return super.x;
}
}

var b:B = new B();
alert(b.method());

它甚至获得了 9 票。但是当你把它贴到官方的 TS playground 上时 http://www.typescriptlang.org/Playground/它给你和错误。

如何从 B 访问 A 的 x 属性?

最佳答案

使用 this 而不是 super :

class A {
// Setting this to private will cause class B to have a compile error
public x: string = 'a';
}

class B extends A {
// constructor(){super();}
method():string {
return this.x;
}
}

var b:B = new B();
alert(b.method());

关于inheritance - 你如何访问 Typescript 中基类的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19287335/

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