First implement it as a regular object, then add other syntaxes after:
var log = {}; log.write = function() { // stuff... return this; }; log.print = function() { // stuff... return this; }; log.reset = function() { // stuff return this; };
Since the function is also an object, it can have properties, so you can replace var log = {}; to a function that redirects to log.write .
function log() { return log.write.apply(log, arguments); }
Finally, for the self-reset syntax, you can find a new instance, but instead of creating a new object, you reset register and pass the same object!
So, now the log function will look like this:
function log() { if (this instanceof log) { return log.reset.apply(log, arguments); } return log.write.apply(log, arguments); }
You can look at jsFiddle to see that it works. Warning: many warnings () on this page!
source share