Search code examples
javascriptwebstorm

Webstorm: Memorized getter trickers warning about "read-only property"


Background

When I use a memorized getter like this:

var myModule = {

    get foo () {
        delete this.foo;
        return this.foo = 'something'
    }
};

in Webstorm I receive the warning:

Property is read-only

Question

Why do I get this warning and can I make it disappear?


Solution

  • WebStorm seems to show the warning because assignments to accessor properties without a setter are ignored in non-strict mode and throw in strict mode.

    And that could be a problem indeed, in case you want to change the value of foo but the getter has not been called yet.

    Therefore, a better practice could be defining a setter too

    var myModule = {
      set foo (val) {
        delete this.foo;
        this.foo = val;
      },
      get foo () {
        delete this.foo;
        return this.foo = 'something';
      }
    };
    

    Then WebStorm should recognize the setter and thus not show the warning.