javascript - "use strict" inheritance / scope -


//global scope "use strict"; //1 function a() {     "use strict"; //2     function innera() {         "use strict"; //3     } } 

i wondering:

is doing use strict @ //1 enough or have explicit @ places //2 , //3.

quoting mdn on strict mode,

to invoke strict mode entire script, put exact statement "use strict"; (or 'use strict';) before other statements.

concatenating strict , non-strict scripts problematic. recommended enable strict mode on function-by-function basis.

so putting @ top applies entire file. don't have explicitly mention in every function.

note: using use strict @ top has own problems. read them in linked mdn page. so, recommended approach, per mdn is

you can take approach of wrapping entire contents of script in function , having outer function use strict mode. eliminates concatenation problem means have explicitly export global variables out of function scope.


you can test that, this

'use strict';  (function () {     return {         1: 1,         1: 2     }; })(); 

now, throw error,

syntaxerror: duplicate data property in object literal not allowed in strict mode

but, when this

(function () {     return {         1: 1,         1: 2     }; })();  (function () {     'use strict';     return {         1: 1,         1: 2     }; })(); 

it fail in second function, not in first function. because, second function in strict mode.

also, if had function within function, have shown in question,

(function () {     'use strict';     (function () {         return {             1: 1,             1: 2         };     })(); })(); 

the inner function in strict mode because of use strict in enclosing function. so, inner function raise syntaxerror.


but, if use use strict in block within {}, not have effect, example,

(function () {     {         'use strict';         return {             1: 1,             1: 2         };     } })(); 

or

console.log("");  'use strict';  var = {     1: 1,     1: 2 }; 

will not throw error.


so, use strict should @ beginning of function, or @ beginning of file. code in strict mode.


Comments