我有这个类结构:
class Component{
constructor(name){
this.__name = name;
}
static getName() { return this.__name; }
}
class ComponentChild extends Component{
constructor(){
super("myName");
}
}
当我打电话时
console.log(ComponentChild.getName);
我希望myName
相反,我得到未定义
。
有什么帮助吗?谢谢!!
最佳答案
在 OOP 中,静态属性和函数属于它们声明的类,因此它们无权访问实例属性或函数,因此您需要使该函数成为非静态的。
getName() { return this.__name; }
进一步说明
在 ES6 声明“静态”函数作为构造函数的属性之前,您必须考虑到 JS 不是基于类的而是基于原型(prototype)的 OOP 语言:
function Component(name) {
// ctor logic
}
Component.getName = function(){
// fn logic
}
因此,在“静态”函数中,您的 this 是构造函数。
更新
如果您必须使用静态方法,您可以编写一个访问器函数,例如
class Component {
static getName(instance) {
return instance._name;
}
}
然后将其用作
console.log(Component.getName(instance));
关于JavaScript ES6 - 父类中的静态方法返回子类中设置的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50373087/