在 es6 javascript class 的非静态成员函数中调用 static getter
Call static getter within a non static member function in es6 javascript class
如何从 es 6 中的普通成员函数调用静态函数 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
我可以将说话功能更改为 return
speak() {
console.log( Animal.name + ":"+ this.speech)
}
但这总是会输出 Animal Class 的名称,但我想要的是输出当前 class 的静态名称 属性(例如 "Tiger" 在子 class) 内。我该怎么做?
添加一个非静态get name()
到Animal
class即returnsthis.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();
如何从 es 6 中的普通成员函数调用静态函数 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
我可以将说话功能更改为 return
speak() {
console.log( Animal.name + ":"+ this.speech)
}
但这总是会输出 Animal Class 的名称,但我想要的是输出当前 class 的静态名称 属性(例如 "Tiger" 在子 class) 内。我该怎么做?
添加一个非静态get name()
到Animal
class即returnsthis.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();