0

As the title suggests: Is it possible, and if so how, can I reassign a static property from within a class instance?

i.e.

class MyClass {
  static myStaticString = 'Foo';

  modifyString() {
    myStaticString = 'Bar';
  }
}

const myInstance = new MyClass();
myInstance.modifyString();

console.log(myInstance.myStaticString); // Should print 'Bar'
Alex.Gunning
  • 191
  • 11
  • It's a static variable, which means there's no `myInstance.myStaticString` by definition. Use `MyClass.myStaticString = 'Bar';` and `console.log(MyClass.myStaticString);` –  Feb 24 '18 at 11:52
  • Besides what @ChrisG mentioned note that static property isn't yet part of the javascript standards. [see this question](https://stackoverflow.com/questions/40367392/static-class-property-not-working-with-babel). – sudavid4 Feb 24 '18 at 11:59
  • Yes, I see. Thanks for the info guys :) – Alex.Gunning Feb 24 '18 at 12:23
  • There are no class *variables*. They're properties! As such, you access them using `MyClass.myStaticString` or `this.myStaticString` [inside static methods](https://stackoverflow.com/a/31117358/1048572) – Bergi Feb 24 '18 at 13:40

1 Answers1

0

As @sudavid4 mentioned, static properties are not available yet. Instead what you can try is static getters/setters.

class MyClass {
  static get myStaticString(){
    return this.stringProp;
}

static set myStaticString(propval){
    this.stringProp = propval;
}    
}

And then modify the values

MyClass.myStaticString = "newstr";
Sandesh
  • 487
  • 1
  • 3
  • 8