2017-01-04 67 views
1

如何从es 6类中的普通成员函数调用静态函数?在es6中的非静态成员函数中调用静态getter javascript class

下面是一个例子:

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) 
} 

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

+1

你可以使用'this.constructor.name',至少在你的情况下将工作(静态成员是构造函数的属性和[Object.prototype.constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor)正在帮助你疗法E)。但是,我不确定这是否是最好的/最干净的解决方案。 – ASDFGerte

+0

为什么它是静态的? –

回答

2

添加非静态get name()Animal类返回this.constructor.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();

+0

谢谢!精美的作品。 –