2

Let's say I have a logging class called Logger.

let log = new Logger(...);

Is it possible to specify a magic method in that class to be executed when the class instance is invoked as function? For example

log(...)

In php implementing the __invoke() magic method of a class achieves the same thing.

1
  • 1
    You can return a function from your Logger constructor, but it will be an arbitrary function not an instance (not inheriting from Logger.prototype)
    – Bergi
    Commented Apr 13, 2016 at 12:05

1 Answer 1

3
function Logger() {
  return function log(arg1, arg2) {
    //@TODO: use the function's args
    // or the arguments property to
    // generate the log

    console.log(log.arguments);
  }
}
logger = new Logger();
logger('boom', 123, 'yolo');

This solution should to the trick you are looking for. How optimal it is or better ways of setting this up will probably be found in the comments below.

2
  • 1
    Please don't forget to include the drawbacks of this approach in your answer.
    – Bergi
    Commented Apr 13, 2016 at 12:14
  • 1
    But this way Logger is not a class anymore, just a function.
    – M--
    Commented May 3, 2016 at 20:07

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.