Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

Can I use non-static variables when initializing static variables in a JavaScript class?

Can I use non-static variables during initialization of static variables in a JavaScript class?
If it's possible, then in which cases can I use it?
In my test code, it doesn't work like I expected:

class Test1 {
  static commonParam = [
    ['Test1', ['Test1', 'Test2', this.param1]]
  ];
  constructor(param1) {
    this.param1=param1;
    console.log(`Test1 param1: ${this.param1}`);
  };
  pintCommonparam(){
     console.log(JSON.stringify(Test1.commonParam));
  }
}

t1 = new Test1(1);
t1.pintCommonparam();

code execution result:

> "Test1 param1: 1"
> "[["Test1",["Test1","Test2",null]]]"

I expected that instead of null the last value of the array would be equal to the value of this.param1

question from:https://stackoverflow.com/questions/65936085/can-i-use-non-static-variables-when-initializing-static-variables-in-a-javascrip

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Static variables are initialized when you create your class, while constructor runs after using new Test1(1). It means that commonParam takes the value before you run class constructor and this.param1 is actually null.

You can try to redefine static variable in constructor like:

constructor(param1) {
    this.param1=param1;
    Test1.commonParam = [
      ['Test1', ['Test1', 'Test2', param1]]
    ];
    console.log(`Test1 param1: ${this.param1}`);
};

Remember that every single object will modify this static variable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...