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

标签 javascript node.js ecmascript-6 es6-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)
}

但这总是会输出 Animal 类的名称,但我想要的是输出当前类的静态名称属性(例如子类中的“Tiger”)。我该怎么做?

最佳答案

将非静态get name()添加到返回this.constructor.nameAnimal类:

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

关于javascript - 在 es6 javascript 类的非静态成员函数中调用静态 getter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41466282/

相关文章:

javascript - 数组数组与 Lodash 的比较

javascript - 使用 Knockout.js 数组过滤器删除元素的 id

javascript - JQuery:通过按下旧文本来更改文本

javascript - 值得麻烦地提交 package-lock.json 吗?

javascript - 显示和映射多个键及其对象数据

typescript - 在 Typescript 的 NodeList 上使用扩展运算符

javascript - HTTP 文件下载 : Monitoring Download Progress

javascript - KnockoutJS - 如何使用 Observable 数组在 foreach 中隐藏某些元素?

javascript - 选择的值未显示在输入值中

javascript - 在方法对象上循环 Pomise