0

I am trying to make a module that has the following interface:

log("hello") // which is doing the same if you wrote console.log("hello")
log.success("good job!")

After 10 hours of trying, failing, testing, researching, this is the summary of what I've arrived at by the end:

class log {
  constructor(...message) {
    console.log(...message);
  }
  static success(...message) {
    console.log(...message, "In green color :)");
  }
}

The problem with my code is that whenever I want to use log("hi"), I'll have to write the new keyword, so I will have to write new log("hi")

So I tried to wrap the new keyword in a function, so

class x {
  constructor(...message) {
    console.log(...message);
  }
  static success(...message) {
    console.log(...message, "In green color :)");
  }
}
const log = (...message) => new x(...message);

The problem with this solution is that although this is helping me to get rid of the new keyword, it's breaking the second part of the app, by now you can not write log.success()

Please note: I'm being aware also of something important, I don't want to invoke the constructor each time I want to call the success method, meaning that I don't want to write log().success() to do my job.

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Ekmek
  • 413
  • 2
  • 12
  • You need a function, not a class: https://jsfiddle.net/khrismuc/haLz391x/ –  Jan 19 '21 at 19:25
  • @ChrisG, Do you believe that this is a good practice? I was thinking of why we don't create an instance from a constructor function and putting the success method on the prototype object of that instance. Why pasting the success method on the original function object? – Ekmek Jan 19 '21 at 19:27
  • Not sure if it's good practice but afaik it's the only way to create the syntax you want. The first use case mandates that `log` is a function, so this is the only way to do it, afaik. Here's more info: https://stackoverflow.com/questions/8588563/adding-custom-properties-to-a-function –  Jan 19 '21 at 19:30
  • Thanks, @ChrisG, do you think that ES6 proxies may also help? – Ekmek Jan 19 '21 at 19:33
  • I don't see how proxies would help here. Why not use the code I posted? A function is an Object, so assigning properties works as expected. If you're uncomfortable with that for reasons, just use a different setup, like `log.print()` and `log.success()`. –  Jan 19 '21 at 19:38
  • @ChrisG, Thanks for the help, I believe that the method you mentioned is the only way of doing it at least in JavaScript. – Ekmek Jan 19 '21 at 21:22

1 Answers1

1

If you don't want to use a constructor or a new keyword, consider using regular function, it would be a good fit for this case:

function log(message) {
  console.log(message);
}
log.success = function(message) {
  console.log(message, "In green color :)");
}

log('hi');
log.success('hi');
Zac
  • 1,497
  • 9
  • 11