Can I extend the console object (for rerouting the logging) in javascript?

前端 未结 6 1830
误落风尘
误落风尘 2020-11-30 08:33

Is it possible to extend the console object?

I tried something like:

Console.prototype.log = function(msg){
    Console.prototype.log.call(msg);
             


        
6条回答
  •  北海茫月
    2020-11-30 09:09

    // console aliases and verbose logger - console doesnt prototype
    var c = console;
    c.l = c.log,
    c.e = c.error,
    c.v = c.verbose = function() {
        if (!myclass || !myclass.verbose) // verbose switch
            return;
        var args = Array.prototype.slice.call(arguments); // toArray
        args.unshift('Verbose:');
        c.l.apply(this, args); // log
    };
    
    // you can then do
    var myclass = new myClass();
    myclass.prototype.verbose = false;
    // generally these calls would be inside your class
    c.v('1 This will NOT log as verbose == false');
    c.l('2 This will log');
    myclass.verbose = true;
    c.v('3 This will log');
    

    I noted that the above use of Array.prototype.unshift.call by nitesh is a better way to add the 'Verbose:' tag.

提交回复
热议问题