In depth understanding of javascript Strict Mode of Strict Mode

  • 2020-03-30 04:24:37
  • OfStack

What strict patterns can do ?

Strict patterns introduce a lot of changes to JavaScript, and I've divided them into two categories (obvious and subtle). The goal of subtle improvements is to fix some of the details of the current JavaScript that I won't go into here; If you are interested, please read the wonderful document ecma-262-5 in Detail Chapter 2 Strict Mode by Dmitry Soshnikov. Here I focus on the obvious changes introduced by strict patterns, the concepts you should know before you use strict patterns, and the changes that will help you the most.

Before you start learning about specific features, remember that one of the goals of strict patterns is to make debugging faster and easier. A runtime that explicitly throws errors when it sees a problem is better than one that silently fails or behaves strangely (as is often the case with JavaScript runtime environments that don't have strict mode turned on). Strict mode throws more errors, but that's a good thing, because these errors call your attention and fix a lot of potential problems that were previously hard to find.

Remove WITH keyword

First, the with statement is removed from strict mode, where the code containing the with statement throws an exception. So the first step in using a strict pattern is to make sure you don't use with in your code.


//In strict mode the following JavaScript code throws an error
with (location) {
    alert(href);
}

Prevents unexpected assignments to global variables

Second, local variables must be declared before they can be assigned. Before strict mode is enabled, a global variable with the same name is automatically created when replicated for an undeclared local variable. This is one of the most common errors in a Javacript program, with an explicit exception thrown when trying to do this in strict mode.


//An exception
is thrown in strict mode (function() {
    someUndeclaredVar = "foo";
}());

THIS in the function no longer refers to the global by default

Another important change in strict mode is that the undefined or undefined this in the function no longer points to the global environment by default. This causes some code execution errors that depend on the default this behavior in the function, such as:


window.color = "red";
function sayColor() {
    alert(this.color);
}
//Errors are reported in strict mode, and "red"
if not in strict mode sayColor();
//Errors are reported in strict mode, and "red"
if not in strict mode sayColor.call(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 previously defined new keyword.


function Person(name) {
    this.name = name;
}
//In strict mode, an error
is reported var me = Person("Nicholas");

In the above code, when the Person constructor runs because there was no new before, the this in the function will remain undefined, and since you can't set a property for undefined, the above code will throw an error. In non-strict mode, this that is not copied by default points to the window global variable, and the result is to accidentally set the name property for the window global variable.

To prevent the nuptial

When writing a lot of code, object properties and function arguments can easily be set to duplicate names. Strict mode explicitly throws an error in this case


//Duplicate variable name, in strict mode will report an error
function doSomething(value1, value2, value1) {
    //code
}
//Duplicate object property names, error reported in strict mode :
var object = {
    foo: "bar",
    foo: "baz"
};

All of the above code is considered a syntax error in strict mode and will let you know before execution.

The safety of the EVAL ()

Although the eval() statement was not eventually removed, it was still improved in strict mode. The biggest change is that the variable and function declarations that are executed in eval() do not directly create the corresponding variable or function 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 kept in eval(). But you can explicitly get the result of an eval() from the return value of an eval() statement, for example:


(function() {
    var result = eval("var x = 10, y = 20; x + y");
    //Run the rest of the statement correctly in strict or non-strict mode (resulst is 30)
    alert(result);
}());

An exception is thrown when a read-only property is modified

ECMAScript5 also introduces the ability to make certain properties of an object read-only, or to make the entire object unmodifiable. But in non-strict mode, trying to modify a read-only property is a silent failure. This is likely to happen when you're dealing with native browser apis. Strict mode explicitly throws an exception in this case, reminding you that modifying this property is not allowed.


var person = {};
Object.defineProperty(person, "name" {
    writable: false,
    value: "Nicholas"
});
//

>
>
>
person.name = "John";

In the above example, the name attribute is set to read-only, and a change to the name attribute in a non-strict mode does not cause an error, but the change does not succeed. Strict mode explicitly throws an exception.

NOTE: it is strongly recommended that you turn strict mode on when specifying using any ECMAScript property feature.

How to use ?

It's very easy to turn strict mode on in modern browsers, just by showing the following command in your JavaScript code

"Use strict";
 


//Please don't use
this way "use strict";
function doSomething() {
    //This part of the code will run in strict mode
}
function doSomethingElse() {
    //This part of the code also runs in strict mode
}

 
The code above doesn't seem like a big problem, though. But when you're not responsible for maintaining all of the code introduced on the page, doing so in strict mode can cause problems if third-party code isn't ready for strict mode.

Therefore, it is best to apply instructions that enable strict mode to functions, such as:


function doSomething() {
    "use strict";
    //The code in this function will run in strict mode
}
function doSomethingElse() {
    //The code in this function does not run in strict mode
}

 
If you want to make strict mode in more than one function in the open, please use the immediate execution function expression (immediately - invoked the function expression, IIFE) :


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

conclusion

Advantages of strict mode:

Make JavaScript more robust
1.           This is no longer encapsulated. In normal mode, This is always an object.
2.           Fun. The caller and Fun. The arguments are not can delete attributes, also can not be set or retrieved.
3.           The Arguments. The caller is not can delete attributes, also cannot set or retrieved.

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


Related articles: