Home  >  Article  >  Web Front-end  >  In-depth understanding of javascript strict mode (Strict Mode)_javascript skills

In-depth understanding of javascript strict mode (Strict Mode)_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:29:521551browse

The strict mode introduced in ECMAScript5 allows developers to have a "better" JavaScript language by allowing the JavaScript runtime environment to handle some of the most common and hard-to-find errors in the development process differently than currently. For a long time, I was skeptical about strict mode since only Firefox supported it. But today, all major browsers have supported strict mode in their latest versions (including IE10, Opera12 and Android4, IOS5). It is time to start using strict mode.

What role does strict mode play?

Strict mode introduces a lot of changes to JavaScript, and I divide them into two categories (obvious and subtle). The goal of minor improvements is to fix some detailed problems in current JavaScript, which I won't go into in depth here; if you are interested, please read the excellent document ECMA-262-5 in Detail Chapter 2 Strict Mode by Dmitry Soshnikov. I'll focus here on the obvious changes introduced by strict mode, the concepts you should know before using strict mode, and the changes that will help you the most.

Before you start learning specific features, please remember that one of the goals of strict mode is to allow you to debug faster and more conveniently. It is better for the runtime environment to explicitly throw an error when it detects a problem than to silently fail or behave strangely (as is often the case with JavaScript runtime environments that do not enable strict mode). Strict mode will throw more errors, but that's a good thing, because these errors will call your attention and fix many potential problems that were previously difficult to find.

Remove WITH keyword

First of all, the with statement is removed from strict mode. Code containing the with statement will throw an exception in strict mode. So the first step to using strict mode: Make sure you don’t use with in your code.

Copy code The code is as follows:

// The following JavaScript code will throw an error in strict mode
with (location) {
alert(href);
}

Prevent accidental assignment of global variables

Secondly, local variables must be declared before assigning a value. Before strict mode is enabled, copying an undeclared local variable will automatically create a global variable with the same name. This is one of the most common errors in Javascript programs, and an explicit exception will be thrown when trying to do this in strict mode.

Copy code The code is as follows:

// An 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 in a function that is undefined or empty (null or undefined) no longer points to the global environment (global) by default. This will cause errors in the execution of some codes that rely on the default this behavior in functions, such as:

Copy code The code is as follows:

window.color = "red";
function sayColor() {
alert(this.color);
}
// An error will be reported in strict mode. If not in strict mode, "red"
will be prompted. sayColor();
// An error will be reported in strict mode. If not in strict mode, "red"
will be prompted. sayColor.call(null);

this will remain undefined until it is assigned, which means that when a constructor is executed, if there is no clear new keyword before, an exception will be thrown.

Copy code The code is as follows:

function Person(name) {
This.name = name;
}
//An error will be reported in strict mode
var me = Person("Nicholas");

In the above code, when the Person constructor is run, because there is no new before, this in the function will remain undefined. Since you cannot set properties for undefined, the above code will throw an error. In a non-strict mode environment, this that is not copied will point to the window global variable by default, and the result of the operation will be to accidentally set the name attribute for the window global variable.

Prevent duplicate names

When writing a lot of code, it is easy to accidentally set object properties and function parameters to a duplicate name. Strict mode will explicitly throw an error in this case

Copy code The code is as follows:

//Duplicate variable names will report an error in strict mode
function doSomething(value1, value2, value1) {
//code
}
//Duplicate 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 you will be prompted before execution.

Safe EVAL()

Although the eval() statement was not ultimately removed, some improvements were still made to it in strict mode. The biggest change is that variable and function declarations executed in eval() will not directly create corresponding variables or functions in the current scope, for example:

Copy code The code 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 clearly obtain the execution result in eval() from the return value of the eval() statement, for example:

Copy code The code 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);
}());

Exception thrown when modifying read-only properties

ECMAScript5 also introduces the ability to set specific properties of an object as read-only, or to make the entire object unmodifiable. But in non-strict mode, trying to modify a read-only property will fail silently. You are likely to encounter this situation when you are dealing with some browser native APIs. Strict mode will explicitly throw an exception in this case to remind you that modifying this property is not allowed.

Copy code The code is as follows:

var person = {};
Object.defineProperty(person, "name" {
writable: false,
Value: "Nicholas"
});
// In non-strict mode, silent failure occurs, in strict mode an exception is thrown.
person.name = "John";

In the above example, the name attribute is set to read-only. Modifying the name attribute in non-strict mode will not cause an error, but the modification will not be successful. But strict mode will explicitly throw an exception.

NOTE: It is strongly recommended that you enable strict mode when using any ECMAScript property attribute specification.

How to use?

It is very easy to turn on strict mode in modern browsers, just enter the following command in the JavaScript code

"use strict";

Although it seems that the above code is just a string that is not assigned to a variable, it actually instructs the JavaScript engine to switch to strict mode (browsers that do not support strict mode will ignore the above code and will not any impact on subsequent execution). Although you can apply this directive globally or in a certain function, you still have to be reminded not to enable strict mode in the global environment.

Copy code The code 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 like 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 expose you to problems caused by third-party code that is not prepared for strict mode.

Therefore, it is best to apply the instruction to enable strict mode in the function, for example:

Copy code The code 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 an immediately-invoked function expression (IIFE):

Copy code The code is as follows:

(function() {
"use strict";
Function doSomething() {
                // This function runs in strict mode
}
Function doSomethingElse() {
               // This function also runs in strict mode
}
}());

Conclusion

I strongly recommend that you enable JavaScript strict mode from now on, it can help you find unnoticed errors in your code. Don't enable it globally, but you can use IIFE (immediate execution of function expressions) as much as possible to apply strict mode to multiple function scopes. At the beginning, you will encounter error messages that you have not encountered before. This is normal. When enabling strict mode, be sure to test in supported browsers to identify new potential issues. Don't just add a "use strict" line to your code and assume the rest of the code will work. Finally, start writing better code in strict mode.

Note:
Here is a summary of strict mode support in various browsers.
You can test the current browser's strict mode support on this page.

Advantages of strict mode:

Make JavaScript stronger
1. This is no longer encapsulated. In normal mode, this is always an object.
2. Fun.caller and fun.arguments are not attributes that can be deleted, nor can they be set or retrieved.
3. Arguments.caller is also an attribute that cannot be deleted, nor can it be set or retrieved.

Paves the way for future ECMAScript versions
1. The following reserved words have been added: implements, interface, let, package, private, protected, public, static and yield.
2. Method declaration should be placed at the front of the script or method, not in the middle of statements such as if or for.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn