0

After reading How to hide source of Log messages in Console? , I'm confused about how this command works.

I try to not use setTimeout to wrap it, but the console log always show the source of log messages. Even I try to see the stack trace, it just shows nothing like the second line: enter image description here

What does the setTimeout(console.log.bind(console, "something")) do? And it seems cannnot remove setTimeout?

is there any other way to do the same thing?

Community
  • 1
  • 1
North
  • 1,434
  • 1
  • 12
  • 21
  • [`Function.prototype.bind`](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) – Andreas May 25 '16 at 07:35
  • I think we are not able to remove any error from console. Try console.clear() – Ali May 25 '16 at 07:45
  • @Ali I don't want to remove log messages, just want to know how it works. Anyway, thanks. – North May 25 '16 at 08:08

1 Answers1

4

Let's take it piece-by-piece:

  1. What is console.log.bind(console, "something")?

    The Function#bind function creates a new function that, when called, will call the original function using the first argument as this for the call and passing along any further arguments. So console.log.bind(console, "something") creates (but doesn't call) a function that, when it is called, will call console.log with this set to console and passing along "something" as the first argument.

  2. What is setTimeout(x, y)?

    It schedules the function x to be called after y milliseconds by the browser; if you don't supply y, it defaults to 0 (call back immediately, as soon as the current code completes).

So taken together, setTimeout(console.log.bind(console, "something")) schedules a call to console.log after a brief delay.

Using the delay means that the call to console.log doesn't happen directly from the code where you do that; the browser calls console.log directly, not within your code. Consequently, the stack trace doesn't show that it happened in your code, because it didn't.

Community
  • 1
  • 1
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • But why does `console.log` need to make `this` to `console`, what the differences between binding and without binding? – North May 25 '16 at 08:06
  • @North: On some (not all) browsers, if you call `console.log` with the wrong `this`, it fails. (Chrome, for instance.) Internally, apparently, the `console` object does use `this` to refer to its own properties, etc. – T.J. Crowder May 25 '16 at 08:29