Can I create my own function with the same name as the existing one to configure it?

I have several console.log commands distributed through my site.

Is it possible to override console.log using my own function? I want to configure the function so that it is registered only if a certain variable is set to true.

In the end, I still need to call the real .log console from this function.

Thanks Kevin

+5
source share
3 answers

Just create a closure and save the original function console.login a local variable.
Then override console.logand call the original function after checking:

(function(){
    var original = console.log;

    console.log = function(){
        if ( log ) { // <-- some condition
            original.apply(this, arguments);
        }
    };
})();

: http://jsfiddle.net/J46w8/

+4

console.log().

var reallog = console.log;
console.log = function(s) {
    if(s == "a") {
        reallog("a");
    }
}
console.log("b");
0
console.constructor.prototype.log = function(msg) {
    alert(msg);
};
0
source

All Articles