1

I think it might be related to the test using PhantomJS, that the test will fail due to some console.log and I need to put a line:

var console = window.console;

at the top inside the IFFE, such as:

(function() {
    var console = window.console;

    // ...
}());

That is a bit strange. First of all, isn't PhatomJS based on webkit, and I thought console and console.log are both defined.

Second, I thought if window.console is defined, and we set it using var console = window.console; then actually, if we don't defined the local console, when console is encountered, then the browser will automatically resolve to window.console because the global environment is window?

I think if the console.log(...) statements were replaced by window.console.log(...) then var console = window.console; won't be needed.

So why is the line var console = window.console; needed and what does it help solve?

nonopolarity
  • 146,324
  • 131
  • 460
  • 740

1 Answers1

0

In the case that window.console is defined, the line has no effect.

In the case that window.console is not defined, the defines console as a valid identifier within the function scope. Without the line, the identifier console would produce a ReferenceError, but window.console simply gets you undefined.

Thus, the line defines console in the case that it's not already an extant identifier, or it uses the value of the global console in the case that it is an extant identifier.

Thus, we can conclude that in your test environment, window.console is not defined.

apsillers
  • 112,806
  • 17
  • 235
  • 239
  • but why will `console.log(123)` fails without `var console = window.console;` – nonopolarity Jun 26 '13 at 15:48
  • To be clear: does the console output actually work? is `console.log` also being defined anywhere? – apsillers Jun 26 '13 at 16:05
  • `console.log()` doesn't work, unless if you use `window.console.log()`, or if you use `var console = window.console;` first – nonopolarity Jun 28 '13 at 12:19
  • @動靜能量 Interesting. In that case, `window` must not be the global object here. You can check what the global object is with `var myglobal = Function('return this')();` ([source](http://stackoverflow.com/q/3277182/710446)), and compare `myglobal == window`. – apsillers Jun 28 '13 at 13:09
  • can't you just `console.log(this)` or check `this === window` – nonopolarity Jun 29 '13 at 09:09
  • @動靜能量 Not if you're in strict mode -- in that case, `this` will be `null` (or `undefined`? one of those). Using the `Function` constructor with a string circumvents this issue and gets the real global object. – apsillers Jun 29 '13 at 11:32