TransWikia.com

default value for calling an object without properties

Stack Overflow Asked by Ekmek on March 4, 2021

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.

One Answer

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');

Correct answer by Zac on March 4, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP