Preface
The strict pattern introduced in ECMAScript5 allows developers to have a "better" JavaScript language by allowing the JavaScript running environment to deal with some of the most common and difficult to detect errors in the development process. For a long time, I had doubts about strict mode because only Firefox supports strict mode. But today, all mainstream browsers support strict mode in their latest versions (including IE10, Opera12 and Android 4, IOS5). It's time to start using strict mode.
What role can strict model play?
Strict pattern introduces a lot of changes to JavaScript, and I divided them into two categories (obvious and subtle). The goal of minor improvements is to fix some of the details in JavaScript, which I will not go into in-depth with here; I will mainly introduce the obvious changes introduced by strict mode, concepts that you should know before you use strict mode and those changes that will help you the most.
Before you start learning specific features, remember that one of the major goals of strict mode is to enable you to debug faster and more conveniently. It is better to throw an explicit error when the runtime environment discovers a problem than to fail silently or act weirdly (which is often the case with JavaScript running environments that do not turn on strict mode). Strict mode throws more errors, but that's a good thing because these errors will draw your attention and fix many potential issues that were previously difficult to spot.
1. Remove the with keywords
First, the with statement is removed in the strict mode, and the code containing the with statement will throw an exception in the strict mode. So the first step to using strict mode: make sure that you don't use with in your code.
// The following JavaScript code will throw an error in strict modewith (location) { alert(href); }
2. Prevent unexpectedly assigning values to global variables
Secondly, local variables must be declared before assignment. Before strict mode is enabled, a global variable with the same name is automatically created when copying for an undeclared local variable. This is one of the most common errors in Javascript programs, and when trying to do this in strict mode, there will be explicit exceptions thrown.
// Exception will be thrown in strict mode(function() { someUndeclaredVar = "foo"; }());
3. This in the function no longer points to the global by default
Another important change in strict mode is that this function that is not defined or undefined (null or undefined) does not point to the global environment by default. This will cause some code execution errors that depend on the default behavior of this in the function, for example:
= "red"; function sayColor() { alert(); } // An error will be reported in strict mode. If it is not in strict mode, it will prompt "red"sayColor(); // An error will be reported in strict mode. If it is not in strict mode, it will prompt "red"(null);
This will remain undefined until it is assigned, which means that when a constructor is executed, an exception will be thrown if there is no clear new keyword before.
function Person(name) { = name; } //There will be an error in strict modevar me = Person("Nicholas");
In the above code, because there is no new before, this in the function will be left undefined. Since you cannot set properties for undefined, the above code will throw an error. In non-strict mode environments, this is not copied to the window global variable by default, and the result of running will be unexpectedly setting the name attribute for the window global variable.
4. Prevent renames
When writing a lot of code, object properties and function parameters are easily accidentally set to a duplicate name. Strict mode will explicitly throw errors in this case
//Dull variable names will report an error in strict modefunction doSomething(value1, value2, value1) { //code } //Dull object attribute names will report an error in strict mode:var object = { foo: "bar", foo: "baz" };
The above code will be considered a syntax error in strict mode and will allow you to get prompts before execution.
5. Safe eval()
Although the eval() statement was not removed in the end, it was still improved in strict mode. The biggest change is that variables and function declarations executed in eval() will not create corresponding variables or functions directly in the current scope, for example:
(function() { eval("var x = 10;"); // In non-strict mode, alert 10// In strict mode, an exception is thrown because x is not defined.alert(x); }());
Any variables or functions created during the execution of eval() are retained in eval(). But you can explicitly get the execution result in eval() from the return value of the eval() statement, for example:
(function() { var result = eval("var x = 10, y = 20; x + y"); // The remaining statements can be run correctly in strict or non-strict mode. (resulst is 30)alert(result); }());
6. Throw an exception when modifying read-only attributes
ECMAScript5 also introduces the ability to set specific properties of an object to read-only, or make the entire object unmodified. However, in non-strict mode, trying to modify a read-only property will only fail silently. This is likely to happen to you during your dealing with some browser native APIs. Strict mode will explicitly throw exceptions in this case, reminding you that modifying this property is not allowed.
var person = {}; (person, "name" { writable: false, value: "Nicholas" }); // In non-strict mode,The failure of silence,In strict mode, an exception is thrown.
= "John"; In the above example, the name attribute is set to read-only. Executing modification of the name attribute in non-strict mode will not cause an error, but the modification will not be successful. But the strict mode will clearly throw exceptions.
NOTE: It is strongly recommended that you enable strict mode when specifying any ECMAScript attributes.
How to use it?
It is very easy to enable strict mode in modern browsers, just need to appear the following command in JavaScript code:
"use strict";
Although the above code seems to be just a string that does not give a certain variable, it actually indicates that the JavaScript engine switches to strict mode (browsers that do not support strict mode will ignore the above code and will not have any impact on subsequent execution). Although you can apply this instruction to a global or a function, here we should remind you not to enable strict mode in a global environment.
// Please don't use it like this"use strict"; function doSomething() { // This part of the code will run in strict mode} function doSomethingElse() { // This part of the code will also run in strict mode}
Although the above code doesn't seem to be a big problem. But when you are not responsible for maintaining all the code introduced in the page, using strict mode in this way will cause you to have problems caused by third-party code not being prepared for strict mode. Therefore, it is best to use instructions that enable strict mode in the function, for example:
function doSomething() { "use strict"; // The code in this function will run in strict mode} function doSomethingElse() { // The code in this function will not run in strict mode}
If you want strict mode to be enabled in more than one function, use the Execute function expression immediately
(immediately-invoked function expression ,IIFE): (function() { "use strict"; function doSomething() { // This function runs in strict mode} function doSomethingElse() { // This function also runs in strict mode} }());
in conclusion
I strongly recommend that you enable JavaScript strict mode from now on, which can help you discover errors that you haven't noticed in your code. Don't enable it in a global environment, but you can try to use IIFE (execute function expressions immediately) to apply strict mode to multiple functions.
At the beginning, you will encounter error messages you have never encountered before, which is normal. When strict mode is enabled, make sure to test it in a supported browser to discover new potential issues.
Be sure not to just add a line "use strict" to the code and assume that the remaining code will work properly. Finally, start writing better code in strict mode.
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.