0

Following this solution I have the following class:

com.temp.System = class {
    static initialize() {
        this.foo = 9;
        console.log("foo 1 is: " + this.foo);
    }

    static testMe() {
        console.log("foo 2 is: " + this.foo);
    }
}

This is how I use it:

{
    const System = com.temp.System;
    System.initialize();
    System.testMe();
}

And this is output:

foo 1 is: 9
foo 2 is: 9

And I have two questions:

  1. What is the best way to create static fileds in such solution?
  2. Why this.foo works although I don't create instances of this class?
Pavel_K
  • 10,748
  • 13
  • 73
  • 186
  • 2
    1. You have created those already 2. Because `System` is an object and objects in JS may have properties. – zerkms Feb 25 '18 at 10:02
  • 2
    [Don't use `class`es with only static properties at all!](https://stackoverflow.com/a/29895235/1048572) – Bergi Feb 25 '18 at 10:07

4 Answers4

3

What is the best way to create static fields in such solution?

Do not use class syntax if you don't want to create instances of it.

com.temp.System = {
//                ^ simple object literal
    initialize() {
        this.foo = 9;
        console.log("foo 1 is: " + this.foo);
    },
    testMe() {
        console.log("foo 2 is: " + this.foo);
    }
};

Why this.foo works although I don't create instances of this class?

Because it's not an instance property. You've created System.foo = 9. this in a method is just the object that the function was called on - which is the namespace object in your example System.initialize().

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
2

this inside a static method points to just the class, so when you called initialize it resulting in adding a property foo to the class instead of an instance. This is why it was defined when you called testMe

Jiby Jose
  • 3,745
  • 4
  • 24
  • 32
1

The best way would be to use a plain good old object literal:

com.temp.System = {
  foo: 5,

  initialize() {
    console.log("foo 1 is: " + this.foo);
  },

  testMe() {
    console.log("foo 2 is: " + this.foo);
  }
};
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

From what I know, there's no such thing as static properties in ES6. The question I want to ask, however, is different: why do you need "static class properties"? How is that different from a constant or, if desired to be accessible from the outside of your class, an exported constant?

The link above gives an example of creating "static data properties" using either Object.defineProperty or just direct assignment to a class MyClass.static = .... However, don't use it unless you clearly understand why.

oleggromov
  • 116
  • 5