"use strict" inheritance / scope
Quoting MDN on strict mode .
To invoke strict mode for the entire script, place the exact statement
"use strict";
(s'use strict';
) in front of any other statements.Concatenation of strict and non-strict scripts is problematic. Therefore, it is recommended to enable strict mode on a per-function basis.
Thus, its placement at the top applies to the entire file. You don't need to explicitly specify what in every function.
Note. The use use strict
above has its own problems. Read about them on the linked MDN page. So the recommended approach, according to MDN, is
You can also use a way of wrapping all script content in a function and using that outer function in strict mode. This fixes the concatenation problem, but it means you must explicitly export any globals out of scope.
You can check it like this
'use strict';
(function () {
return {
1: 1,
1: 2
};
})();
Now it throws an error,
SyntaxError: property duplicate data in object literal is not allowed in strict mode
But when you do something like this
(function () {
return {
1: 1,
1: 2
};
})();
(function () {
'use strict';
return {
1: 1,
1: 2
};
})();
it will only fail in the second function and not in the first function. Because only the second function is in strict mode.
Also, if you have a function within a function as shown in the question,
(function () {
'use strict';
(function () {
return {
1: 1,
1: 2
};
})();
})();
the inner function will also be in strict mode due use strict
to the enclosed function. So the inner function will increase the value SyntaxError
.
But if you use use strict
in a block inside {}
, it will have no effect, for example
(function () {
{
'use strict';
return {
1: 1,
1: 2
};
}
})();
or
console.log("");
'use strict';
var a = {
1: 1,
1: 2
};
will not throw any errors.
So, use strict
should be at the beginning of a function or at the beginning of a file. Only then will the code be in strict mode.
source to share
Determine it at //1
enough. This is straight from JavaScript: The definitive guide (with emphasis I added):
Top-level (non-functional) script code is strict code if the script has a "use strict" directive. A function body is strict code if it is defined in strict code or has a "use strict" directive.
source to share