A 30-minute presentation given at Dealer.com on May 6, 2011.
An overview of what "strict mode" means ECMAScript 5, and what it means (and does not mean) for everyday web development.
9. "strict mode"; // and then the rest // but be careful when // concatenating! // "more compatible" way: (function(){ "use strict"; // and then the rest })(); How do I invoke it?
10. // "old" way foo = 'is now global'; "use strict"; bar = 'is not global'; // throws a ReferenceError Won’t let you do dumb things:implicit globals
11. // "old" way foo = { bar: function(){}, baz: 'name' }; with(foo){ bar(baz); } "use strict"; foo = { bar: function(){}, baz: 'name' }; with(foo){ bar(baz); } // ERROR! Won’t let you do dumb things:WITH(){}
12. …and other things you know better than to try and do in the first place. "use strict"; delete undeclaredVariable; // ERROR! var foo = { eval: function(val){} }; // ERROR! var arguments = somethingGlobal; // ERROR! varNaN = 'not a number'; // ERROR! var Infinity = (getAllNaturalNumbers() / 2); // ERROR! var undefined = 'undefined'; // ERROR!
13. // "old" way eval("that = 'this and that!';"); console.log('that is...:', that); "use strict"; eval("that = 'this and that!';"); console.log('that is...:', that); // ERROR! Not without controversy
14. // "old" way (function(){ console.log( 'this is...:', this ); })(); // this == window "use strict"; (function(){ console.log( 'this is...:', this ); })(); // this == undefined Not without controversy
15. Not without controversy "use strict"; function factorial(num){ if (num <= 1) { return 1; } else { return num * arguments.callee(num-1); } } // ERROR!
( Firefox has had it for quite some time… Chrome and Safari have it now… IE9? )
Invoked as either- The first line in a whole JS file –or-- As the first line in a function
Enforcing some rules that were common sense… and/or were not exactly built-in but should have been……and/but then we get to the controversy? (who in here has seen 'undefined' get defined as such for the sake of old IE versions?)
But this isn't much of a controversy? - - restrictions on eval() are a blessing
But this might get some hackles up… There's that whole bit about `this` being "broken" in JavaScriptBut if you're expecting `this` to scope up to `window`… now you have broken code
Firefox 4 will complain:'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them
it's opt-in – so you'd have to decide to use itAnd anyway it's just enforcing certain coding styles that you ought to be doing anywayAnd/but you're already linting right?And/but there is an argument to be made for NOT using it