As a learning experience, I'm trying to make my own little console debug script that is object-oriented. I want it to be similar to jQuery in that you can call it as a function (jQuery('div')
) or as an object (jQuery.ajax()
).
I have the code below which is almost working. It is basically an alias of "console.log".
My goal is to be able to perform the following:
var log = new RadDebug;
// Create our function
log('You selected: %s', fruit_type);
// Invoke the top-level function
// Output: You selected: "Apple"
log.warn('You selected: %s', fruit_type);
// Invoke a method "warn", which displays a caution icon next to the log.
// Output: (!) You selected "Apple"
The script I am working on:
function RadDebug() {
var debug_enabled = (debug_mode && window.console && window.console.log instanceof Function);
// If this object was already initialize, redirect the function call to the ".log()" as default
if ( this.initialized ) {
return this.log.apply( this, arguments );
}
this.initialized = true;
this.log = function() {
if ( !debug_enabled ) return;
console.log.apply( console, arguments );
};
this.info = function() {
if ( !debug_enabled ) return;
console.info.apply( console, arguments );
};
// More methods below
}
The problem:
Calling log.warn("hello world")
works as you would expect.
Calling log("hello world")
tells me that TypeError: Object is not a function
.
Question: How do I get it to work as a function and having object-like properties? (Like how jQuery does it)
(This question has been resolved thanks to @FelixKling. The final code is available as a Gist if you want to check it out).