[英]What's going on in the Static method in javascript es6?
在我的代码中
import A from './A'
import B from './B'
export default class App extends React.Component{
constructor(){
console.log(B.getInstance()); // Why A.getInstance() got called ???
}
}
A.js(B.js相同)
export default class A extends React.Component{
static instance = null;
static getInstance(){
return A.constructor.instance;
}
componentWillMount(){
A.constructor.instance = this;
}
}
我的类A和B都有“静态getInstance()方法”。 在这里,我调用了“ B类”,但是调用了A的getInstance()。 这里发生了什么?
我应该避免为静态方法使用相同的方法名称吗?
谢谢。
我可能会错误地发布我的问题。 我发布了一个新问题,以明确说明我的问题是什么。 谢谢。
让我猜想您是在B组件之后渲染A组件。 由于两个组件都扩展了相同的parent(React.Component)构造函数,因此它们共享。 这意味着,如果将任何内容存储为构造函数的属性,它将与所有子组件共享。
class A {}
class B extends A {
static setSharedKey (){
return B.constructor.sharedKey= 123
}
}
class C extends A {
static getSharedKey (){
return C.constructor.sharedKey
}
}
因此,如果您致电。
B.setSharedKey()
接着
C.getSharedKey() //123
您将获得这样的输出
提供建议以解决此问题我想知道为什么您要尝试从静态方法的实例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.