我无法从类中的静态方法调用私有或非静态方法,下面是示例
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
this.fun1();
}
}
a.staticfun();我试图只公开staticfun方法,它在内部调用所有私有方法,但这让我知道this.fun1不是一个函数。我试着用'this‘找到很多方法来找到它,但它确实有效。
如何在静态方法中调用私有实例方法?
发布于 2018-10-23 18:41:02
fun1不是静态函数,因此您需要定义a类的新实例才能调用它:
class a {
fun1() {
console.log('fun1');
}
static staticfun() {
console.log('staticfun');
new this().fun1();
}
}
a.staticfun();
但是,您应该注意到,这不是一个好的实践。你不应该有一个依赖于非静态逻辑的静态方法。
一种变通办法是将a的一个实例传递给静态函数,但这完全违背了首先使用静态方法的意义。
发布于 2018-10-23 19:06:35
另一种方法是直接从类原型调用函数(字面意思是prototype属性,而不是__proto__),如果您想避免实例化它的话。
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
this.prototype.fun1();
}
}
a.staticfun();发布于 2018-10-23 18:40:47
首先,阅读这个SO question
您可以创建一个a类的实例,然后从该实例调用fun1方法。
但是,从静态方法调用非静态方法是没有意义的。
静态表示此方法属于对象(而不是实例)
class a {
fun1(){
console.log('fun1');
}
static staticfun(){
console.log('staticfun');
const classInstance = new a()
classInstance.fun1();
}
}
a.staticfun();
https://stackoverflow.com/questions/52946944
复制相似问题