0

I have a .js like this and i'm compacting it:

'use strict';
!(function () {
  var object = typeof exports != 'undefined' ? exports : this;
}());

When I use the Google Closure compiler I don't get any erros and the 'this' is referencing the window object. But when I use the Uglify ( with mangle true or false ) it gets a undefined on the 'this' ( so the object is undefined and I receive the error ). Does anyone knows why?

Basically I can just change the this to window and it will work but my concern is about other codes, libs or something else that I'm uglyfing in the future.

Note: I'm using the grunt-contrib-uglify plugin with the options: mangle: true, preserverComments: false, sourceMap: true

  • 1
    So what is the result after minification? – zerkms Mar 20 '15 at 22:01
  • 1
    `typeof exports != 'undefined'` is bad. Make that strict with `!==` – m59 Mar 20 '15 at 22:02
  • @m59 what do you mean by "bad"? Any details? – zerkms Mar 20 '15 at 22:03
  • @m59 it's not bad because the `typeof` operator will definitely return a string. – Pointy Mar 20 '15 at 22:03
  • You guys are defending loose equality? I'm questioning everything I know about programming. Are you saying this is a rare time where it is "ok" just because it can't cause a problem in this case? – m59 Mar 20 '15 at 22:05
  • 1
    @m59 well it's bad if your Douglas Crockford I guess :) If you want to live by and advocate a stricter coding standard then by all means Live Long And Prosper, but the fact is that it won't make any difference in this case. – Pointy Mar 20 '15 at 22:07
  • @m59 I do not defend anything. I'm asking the technical reason why you don't recommend using `!-` here. Any problems with it in *this particular case*? "it is "ok" just because it can't cause a problem in this case" --- it is OK for developer to make thoughtful decisions, not just follow dogmas (that don't have (or do they?) a valid technical reason) – zerkms Mar 20 '15 at 22:08
  • I don't understand the obsession with `===` and `!==` In most cases I know (really really know), what types I'm comparing, so why should I add that extra `=` in the first place? – mmgross Mar 20 '15 at 22:09
  • @mmgross (disclaimer: it's irony) didn't you know `===` operator is faster than `==`? – zerkms Mar 20 '15 at 22:12
  • Btw, can anyone please refer me on where in ES5.1 specification this behaviour with `use strict` is explained? Like when the code is `strict` then `thisBind` is `undefined`. Spent good 10 minutes there but no traces of it. – zerkms Mar 20 '15 at 22:15
  • I don't understand the obsession about micro-optimzations either, so it's probably me who's at fault here. ;) – mmgross Mar 20 '15 at 22:16

1 Answers1

4

It is expected behaviour:

with 'use strict'; a function's context is undefined, not a global object.

zerkms
  • 249,484
  • 69
  • 436
  • 539