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) 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.

Sign up to request clarification or add additional context in comments.

2 Comments

Please don't forget to include the drawbacks of this approach in your answer.
But this way Logger is not a class anymore, just a function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.