0

I'm learning ES6 classes. Is there a way to make helper functions (eg for data munging) accessible to the constructor, but also elsewhere, so that I'm not typing out the function twice (as an IIFE in the constructor and a static class method too)?

Eg at the moment I'm doing because getDimensions is not callable in the constructor:

class Foo {

    constructor(data){
        this._data = data;
        let dimensions = function(data){
            //return some dimensions
        }(data);
        this._x = d3.scaleLinear().domain([dimensions])...
    }

    static getDimensions(someData){
        //same calcs as the constructor IIFE
    }

    updateScale(newData){
        let dimensions = getDimensions(newData);
        this.x = d3.scaleLinear().domain([dimensions]);
    }
}

Is it possible/sensible to get myself a static helper method that I can use in my prototype methods and in the constructor?

Escher
  • 5,418
  • 12
  • 54
  • 101
  • You're calling `getDimensions` in the `updateScale` method not in the constructor, and it's a function call not a static method call? – Bergi Oct 10 '16 at 19:34

2 Answers2

2

getDimensions is a static method, so you have to access it as a property of the Foo object. Instead of getDimensions(newData) you should do Foo.getDimensions(newData).

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177
1

Not sure what you mean. You should be able to call a static method just fine by referencing the class name. Here is a complete example showing calling a static method from one class in the constructor of another:

<html>
   <head>
      <script type="text/javascript" src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
      <script type="text/javascript">
         class Defines {
            static StaticMethod(data) {
               $("#someDiv").append("static method " + data);
            }
         }

         class SomethingConcrete {
            constructor (data) {
               this.data = data;
               Defines.StaticMethod(this.data);
            }
         }

         $(function () {
            const somethingConcrete = new SomethingConcrete(3);
         });
      </script>
   </head>
   <body>
      <div id="someDiv">
      </div>
   </body>
</html>

Outputs: "static method 3"

Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80
  • 2
    Notice that a class which has only static members is an antipattern. – Bergi Oct 10 '16 at 19:35
  • @Bergi depends... for example a `Math` static class is not a problem in most languages, although I guess in javascript you can have functions right in a namespace so there is no need to have them in a class necessarily. – Dave Cousineau Oct 10 '16 at 19:37
  • I meant specifically the `class` syntax, yes. You should use an object literal instead, or even just multiple named export and a namespace import. `Math` should not be callable or have a prototype object. – Bergi Oct 10 '16 at 19:44