How to safely wrap `console.log`?

后端 未结 10 524
日久生厌
日久生厌 2021-01-31 14:13

Suppose I want to include some calls to console.log for some legitimate production reason, say for something like a unit test harness. Obviously I would not want th

10条回答
  •  执念已碎
    2021-01-31 14:52

    coffeescript:

    empty_function = ->
      return
    if !window.console?
      window.console = {}
      for fn in ['log', 'info', 'warn', 'debug', 'error']
        if (typeof window.console[fn] isnt 'function')
          window.console[fn] = empty_function
    

    js:

    (function() {
      var empty_function, fn, i, len, ref;
    
      empty_function = function() {};
    
      if (window.console == null) {
        window.console = {};
        ref = ['log', 'info', 'warn', 'debug', 'error'];
        for (i = 0, len = ref.length; i < len; i++) {
          fn = ref[i];
          if (typeof window.console[fn] !== 'function') {
            window.console[fn] = empty_function;
          }
        }
      }
    
    }).call(this);
    

提交回复
热议问题