【问题标题】:How do you access properties of base class in Typescript?如何在 Typescript 中访问基类的属性?
【发布时间】:2013-10-17 17:10:16
【问题描述】:

有人建议使用这样的代码

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游乐场时 http://www.typescriptlang.org/Playground/ 它给你和错误。

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

【问题讨论】:

    标签: inheritance properties typescript superclass


    【解决方案1】:

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

    【讨论】:

    • 冠军!抱歉,没有足够的声望 +1
    猜你喜欢
    • 2019-07-27
    • 1970-01-01
    • 2011-11-01
    • 2021-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    相关资源
    最近更新 更多