As we know, JavaScript is a flexible language. Its flexibility also brings a lot of pits, and of course some are design flaws. Like what
There is nothing ==
, typeof
such as the pit, countless. After all, JavaScript's father designed the language for only one weeks, hehe.
So what are the simple ways we can avoid some pits?
Coffeescript is a good choice, but there is a cost of learning. The simpler way is to use JavaScript in strict mode.
What is the strict mode of JavaScript
In JavaScript's strict mode, there are some limitations on how JavaScript is written. If these restrictions are violated in strict mode, the code will get an error.
The purpose of setting up the strict model is mainly:
- Reduce some of the unreasonable and less stringent JavaScript syntax, and reduce some of the bizarre behavior
- Eliminate some of the unsafe code runs and keep your code safe
- increase compiler efficiency and increase operating speed
- Pave the future for new versions of JavaScript (some reserved words such as: class, Enum, export, extends, import, super cannot do variable names)
How to use
Specifies that the entire JS file executes strict mode, then the first line of the file is written
"use strict";
Specifies that a method executes strict mode, which is written on the first line of the method "use strict";
, such as
function strict(){ "use strict"; return "这是严格模式。";}
For browsers that do not support strict mode, they are ignored "use strict";
.
Restrictions in strict mode
Only a few of the above are listed, more visit here.
Introduction to JavaScript Strict mode