繁体   English   中英

在es6 javascript类的非静态成员函数内调用静态getter

[英]Call static getter within a non static member function in es6 javascript class

如何在es 6类中从普通成员函数调用静态函数?

这是一个例子:

class Animal {
    constructor(text) {
        this.speech = text;
    }

    static get name() {
        return "Animal";
    }

    speak() {
        console.log( this.name + ":"+ this.speech)
    }
}

class Tiger extends Animal {
    static get name() {
        return "Tiger"
    }
}

var animal = new Animal("hey there");
animal.speak();
var tiger = new Tiger("hello");
tiger.speak();

// output: 
// undefined:hey there
// undefined:hello

我可以将语音功能更改为返回

speak() {
     console.log( Animal.name + ":"+ this.speech)
}

但这总是从动物类中输出名称,但是我想要的是输出当前类的静态名称属性(例如,子类中的“老虎”)。 我怎样才能做到这一点?

向返回this.constructor.nameAnimal类中添加一个非静态的get name()

get name() {
    return this.constructor.name;
}

 class Animal { constructor(text) { this.speech = text; } static get name() { return "Animal"; } get name() { return this.constructor.name; } speak() { console.log( this.name + ":"+ this.speech) } } class Tiger extends Animal { static get name() { return "Tiger" } } var animal = new Animal("hey there"); animal.speak(); var tiger = new Tiger("hello"); tiger.speak(); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM