Skip to content Skip to sidebar Skip to footer

I Get "no Such Method" When Using ES6 Static Functions

I'm trying to create a 'utils' class with static functions in it for a project I work on in react native. I read about how to make static functions in a StackOverFlow question, but

Solution 1:

Good thing you got things working, but I'd just like to add a solution that more closely resembles what you were originally trying to do, and heeds the points made in the SO question you linked.

There is just no need to use class to export bunch of static methods. I don't see how it would add functionality, ease of use or clarity to the code. Quite the contrary actually, the syntax looks more verbose than exporting plain old ES5 style objects and even more so when we bring ES6+ sweetness to the mix.


Your original example of the utils module works just fine. The problem is in the import.

As you are just exporting one default object, the correct way to import it would be

import Utils from './utils/utils';

No brackets, no asterisks, just a name for the imported default object, which can then be used like var text = Utils.textFormat(...).

We can go further, though. By ditching the whole "export one default object" approach, we can use the full power of the module system.

utils.js:

'use strict'

function textFormat(args) {
      var s = args[0];
      ...
      return s;
}

const someOtherUtility = str => str + ' works!';

export { textFormat, someOtherUtility };

Now the exported functions can be used like this

import * as Utils from './utils/utils';

var text = Utils.textFormat(rowData.text, "<Text style={{color:'blue'}}>Hey there</Text>");

Or like this

import {textFormat} from './utils/utils';

var text = textFormat(rowData.text, "<Text style={{color:'blue'}}>Hey there</Text>");

Whichever you prefer.


Solution 2:

You are mixing the two approaches laid out in the linked question, which doesn't work. It should either be

// utils.js
export default {
  textFormat(args) {
    var s = args[0];
    for (var i = 0; i < args.length - 1; i++) {
      var reg = new RegExp("\\{" + i + "\\}", "gm");
      s = s.replace(reg, args[i + 1]);
    }
    return s;
  }
}

// main file
import Utils from './utils/utils';
…
var text = Utils.textFormat(rowData.text, "<Text style={{color:'blue'}}>Hey there</Text>");

or

// utils.js
export function textFormat(args) {
  var s = args[0];
  for (var i = 0; i < args.length - 1; i++) {
    var reg = new RegExp("\\{" + i + "\\}", "gm");
    s = s.replace(reg, args[i + 1]);
  }
  return s;
}

// main file
import * as Utils from './utils/utils';
…
var text = Utils.textFormat(rowData.text, "<Text style={{color:'blue'}}>Hey there</Text>");

(the latter is preferable)


Post a Comment for "I Get "no Such Method" When Using ES6 Static Functions"