sisisisi
sisisisi

Reputation: 621

Javascript class properties - how to assign a function as value to them?

In my javascript code I have a helper class for formatting objects:

class MyHelperClass() {
  get MyStylerFunction() {
    return function(value, index) {
      return "/*some css based on value and index*/";
    };
  }

  get MyFormatterFunction() {
    // similar pattern to MyStylerFunction
  }
}

This code is then used by:

myObj.table({
  title: ...,
  columns: ...,
  cssfunction: MyHelperClass.MyStylerFunction
});

This code doesn't work and gives no error messages on console. As I have no control over the table() function I assume it gracefully fails when the given css getter function is not applicable. However, when I use this:

// inside MyHelperClass
MyStylerFunction(value, index) {
  return "/*some css based on value and index*/";
}

// in function table()
...
cssfunction: MyHelperClass.prototype.MyStylerFunction
...

It works as expected. If I place the styler function outside the class and just give the name of the function to table(), it also works:

// in global namespace
function myStylerFunction(value, index) {
  // you know the drill by now
}

// inside table()
...
cssfunction: myStylerFunction
...

The problem is that

  1. I don't want to fill the global namespace with junk
  2. Using prototype feel clumsy, so I want to avoid that if possible

Is there a way to achieve my goal while keeping the MyHelperClass.MyStylerFunction syntax in table()?

I have no idea what causes this problem and googling haven't returned any results on how to correctly return function values from class property getters.

Upvotes: 0

Views: 250

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50749

What you're after are static methods. Static methods don't require an instance of your class to be invoked, instead, they can be accessed on the class itself. This can be used for utility functions which you can pack away into a helper class such as your MyHelperClass. You can also use static getters, which allows you to run code upon accessing the static method.

class MyHelperClass {
  static get MyStylerFunction() {
    return function(value, index) {
      return "/*some css based on value and index*/";
    };
  }

  static get MyFormatterFunction() {
    // similar pattern to MyStylerFunction
  }
}

This will allow you to do the following:

myObj.table({
  title: ...,
  columns: ...,
  cssfunction: MyHelperClass.MyStylerFunction
});

As MyStylerFunction is static, you can access it as a property of the class itself. Moreover, as it's a getter (get), you don't need to invoke it like a normal function/method, instead, it will automatically be invoked, returning the function you specified to be returned.

Upvotes: 1

Related Questions