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?
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?
Share Improve this question asked Mar 5, 2020 at 10:08 WertuWertu 1376 bronze badges 4- ecma-international/ecma-262/6.0/#sec-strict-mode-code – George Commented Mar 5, 2020 at 10:12
-
2
any
type="module"
script is automatically in strict-mode, yes. – ASDFGerte Commented Mar 5, 2020 at 10:13 - @ASDFGerte, so e.g if we have function like function Addition(){'use strict'}, each function inside es module has use strict in itself. Right? – Wertu Commented Mar 5, 2020 at 10:22
-
1
If you are using native JavaScript modules, then all the code within your modules will be in strict mode by default. If you are using older hand-rolled modularisation patterns, then you will need to declare
'use strict'
at the top of the module. – Ben Aston Commented Mar 5, 2020 at 10:23
1 Answer
Reset to default 8Is 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 mon 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>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744964292a4603578.html
评论列表(0条)