Reputation: 137
I was learning JS and came across 'use strict'. Then, here Should I 'use strict' for every single javascript function I write? @Bergi says that "you only should put 'use strict' in the module scope - once per file - so that it is inherited by all your functions". Is it true that by "it is inherited by all your functions" means each function in a certain module uses 'use strict' inside of itself?
Upvotes: 9
Views: 2284
Reputation: 370779
Is it true that by "it is inherited by all your functions" means each function in a certain module uses 'use strict' inside of itself?
A function will run in strict mode if:
(1) The function is inside an ES6 module (these all run in strict mode regardless), or
(2) There is a proper 'use strict'
directive above the function definition, lexically.
In addition to a few less common instances, such as inside a constructor
.
The way 'use strict'
is inherited lexically works the same way variables can be referenced, and how variable scope works - if any outer block of a function is strict, then the inner function is strict as well. So, for example, with the following code:
'use strict';
function foo() {
function bar() {
function baz() {
}
}
}
No matter what other code you put inside foo
, bar
, and baz
, all of those functions, no matter how they're run, will run in strict mode. If one of these function is called from a source which isn't running in strict mode, the called function will still run in strict mode. For example:
<script>
'use strict';
function foo() {
return function bar() {
return function baz() {
console.log('baz running. strict:', this === undefined);
}
}
}
foo()()();
</script>
<script>
// Non-strict script calling strict function:
foo()()();
</script>
Upvotes: 8