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 detailed issues in current JavaScript, which I will not go into in-depth here; if you are interested, please read the wonderful document written by Dmitry Soshnikov ECMA-262-5 in Detail Chapter 2 Strict Mode. I mainly introduce the obvious changes introduced by strict mode, concepts you should know before you use strict mode and those changes that 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 problems that were previously difficult to spot.
Remove 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 code copy is as follows:
// The following JavaScript code will throw an error in strict mode
with (location) {
alert(href);
}
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, explicit exceptions will be thrown.
The code copy is as follows:
// Exception will be thrown in strict mode
(function() {
someUndeclaredVar = "foo";
}());
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:
The code copy is as follows:
window.color = "red";
function saysColor() {
alert(this.color);
}
// 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"
sayColor.call(null);
This will remain undefined before being assigned, which means that when a constructor is executed, an exception will be thrown if there is no clear new keyword before.
The code copy is as follows:
function Person(name) {
this.name = name;
}
//There will be an error in strict mode
var 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.
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
The code copy is as follows:
//Repeated variable names will report an error in strict mode
function 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.
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 directly create corresponding variables or functions in the current scope, for example:
The code copy is as follows:
(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:
The code copy is as follows:
(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);
}());
Throw an exception when modifying read-only attributes
ECMAScript5 also introduces the ability to set specific properties of an object to read-only, or to 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.
The code copy is as follows:
var person = {};
Object.defineProperty(person, "name" {
writable: false,
value: "Nicholas"
});
// In non-strict mode, silence fails, and an exception is thrown in strict mode.
person.name = "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 using 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 means 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.
The code copy is as follows:
// 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:
The code copy is as follows:
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 immediately-invoked function expression (IIFE):
The code copy is as follows:
(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 use IIFE as much as possible (execute function expressions immediately) to apply strict patterns 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 supported browsers to discover new potential issues. Do not 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.
Note:
Here is a summary of the strict mode support situations of each browser.
You can test the strict mode support of the current browser on this page.
Advantages of strict mode:
Make JavaScript stronger
1. This is no longer encapsulated, and under normal mode, this has always been an object.
2. Fun.caller and fun.arguments are not deleteable properties, and cannot be set or retrieved.
3. Arguments.caller is also an attribute that cannot be deleted, nor can it be set or retrieved.
Pave the way for future ECMAScript versions
1. The following reserved words were added: implements, interface, let, package, private, protected, public, static and yield.
2. The method declaration should be placed at the front of the script or method, and cannot be placed in the middle of statements such as if or for.