Deep understanding of JavaScript Strict mode (Strict mode) _javascript tips

Source: Internet
Author: User

The rigorous model introduced in ECMASCRIPT5 allows the developer to have a "better" JavaScript language by allowing JavaScript to run the environment to make and present different processes for the most common and difficult bugs in the development process. For a long time, I had doubts about strict patterns because only Firefox supported the strict model. Today, however, all major browsers have supported strict models (including IE10,OPERA12 and ANDROID4,IOS5) in their latest version, and it's time to start using strict mode.

What is the effect of strict mode?

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 of the details of the current JavaScript, and I'm not going to go into it here; if you are interested, please read the wonderful document written by Dmitry Soshnikov Ecma-262-5 in Detail Chapter 2 Strict Mode. I'm here to introduce the obvious changes introduced by strict patterns, the concepts you should know before you use strict patterns, and the changes that are most helpful to you.

Before you start learning specific features, remember that one of the big goals of strict mode is to make debugging faster and easier. It is better to run an environment when it discovers a problem than to fail or act strangely (as is often the case without opening a strict-mode JavaScript runtime). Strict patterns can throw more errors, but that's good, because these bugs can raise your mind and fix a lot of potential problems that were hard to spot before.

Remove with keyword

First, in strict mode, the With statement is removed, and the code containing the WITH statement throws an exception in strict mode. So the first step in using strict mode is to make sure that you don't use the with in your code.

Copy Code code as follows:

The following JavaScript code throws an error in strict mode
With (location) {
alert (HREF);
}

Prevent accidentally assigning values to global variables

Second, local variables must be declared before they are assigned. Before you enable strict mode, a global variable with the same name is automatically created when you copy an unspecified local variable. This is one of the most likely errors in the Javacript program, and an explicit exception is thrown when trying to do so in strict mode.

Copy Code code as follows:

Exceptions are thrown in strict mode
(function () {
Someundeclaredvar = "Foo";
}());

This in the function no longer defaults to global

Another important change in strict mode is that this one is not defined or NULL in the function (null or undefined) is not the default point to the global environment. This can cause code execution errors for the default this behavior in some dependency functions, such as:

Copy Code code as follows:

Window.color = "Red";
function Saycolor () {
alert (This.color);
}
Error in strict mode, if not in strict mode, prompt "red"
Saycolor ();
Error in strict mode, if not in strict mode, prompt "red"
Saycolor.call (NULL);

This will remain undefined until the value is assigned, which means that when a constructor executes, it throws an exception if there is no explicit new keyword.

Copy Code code as follows:

function person (name) {
THIS.name = name;
}
Error in strict mode
var me = person ("Nicholas");

In the code above, the person constructor runs because there is no new, this in the function is left as undefined, and because you cannot set the property for undefined, the above code throws an error. In a strict-mode environment, this will default to the window global variable, and the result will be an unexpected setting of the Name property for the window global variable.

Prevent duplicate names

When writing a lot of code, object properties and function parameters can easily be inadvertently set to a duplicate name. Strict mode in this case will explicitly throw the error

Copy Code code as follows:

Duplicate variable name, error in strict mode
function dosomething (value1, value2, value1) {
Code
}
Duplicate object property name, which will be an error in strict mode:
var object = {
Foo: "Bar",
Foo: "Baz"
};

The above code is considered a syntax error in strict mode and allows you to be prompted before execution.

Security EVAL ()

Although the Eval () statement was not eventually removed, it was still improved in strict mode. The biggest change is that variables and function declarations executed in eval () do not create corresponding variables or functions directly in the current scope, for example:

Copy Code code as follows:

(function () {
Eval ("var x = 10;");
In non-rigorous mode, alert 10
In strict mode, an exception is thrown because x is not defined.
alert (x);
}());

Any variables or functions created during eval () execution remain in eval (). But you can explicitly get the execution result in eval () from the return value of the eval () statement, for example:

Copy Code code as follows:

(function () {
var result = eval ("var x = ten, y = 20;") x + y ");
The remaining statements can be run correctly in either strict or strict mode. (Resulst is 30)
alert (result);
}());

Throw an exception when modifying a read-only property

ECMASCRIPT5 also introduces the ability to set a specific property of an object to read-only or to make the entire object unreadable. However, in a non strict mode, attempting to modify a read-only property will only fail silently. You are likely to experience this in your dealings with some of the browser's native APIs. Strict mode throws an exception explicitly in this case, reminding you that modifying this property is not allowed.

Copy Code code as follows:

var person = {};
Object.defineproperty (person, "name" {
Writable:false,
Value: "Nicholas"
});
In a non strict mode, silence fails and throws an exception in strict mode.
Person.name = "John";

In the example above, the Name property is set to read-only, and the modification to the Name property in the non-strict mode does not raise an error, but the modification does not succeed. But strict mode will explicitly throw an exception.

Note: It is strongly recommended that you turn on strict mode when you specify using any of the ECMAScript attribute attributes.

How to use it?

It's easy to open strict mode in a modern browser, just to have the following instructions in the JavaScript code

"Use strict";

Although it seems that the above code is just a string that is not assigned a variable, it actually plays a role in instructing the JavaScript engine to switch to strict mode (browsers that do not support strict mode ignore the above code and do not have any effect on subsequent execution). Although you can take this command to a global or a function, here's a reminder not to enable strict mode in the global context.

Copy Code code as follows:

Please don't use that.
"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 code above does not look like a big problem. However, when you are not responsible for maintaining all the code introduced in the page, this use of the strict pattern can lead to problems that arise from the fact that the third party code is not ready for a rigorous model.

Therefore, it is best to apply an instruction that opens a strict mode to a function, for example:

Copy Code code as follows:

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 the strict mode to open in more than one function, use the immediate execution function expression (immediately-invoked function expression, Iife):

Copy Code code 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, which can help you find errors that you haven't noticed in your code. Do not enable in the global environment, but you can use Iife (Execute function expression immediately) to apply strict mode to multiple function scopes as much as possible. It's normal for you to start with the wrong hints you've never encountered before. When strict mode is enabled, make sure that you test in a supported browser to discover new potential problems. Be sure not to add a single line of "use strict" to your code to assume that the remaining code will work correctly. Finally, start writing better code in strict mode.

Note:
Here is a summary of the strict mode support for each browser.
This page can be tested against the strict mode support of the current browser.

The advantages of Strict mode:

Make JavaScript more secure
1. This is no longer encapsulated, and this is always the object under normal mode.
2. Fun.caller and fun.arguments are not properties that can be deleted and cannot be set or retrieved.
3. Arguments.caller is also not allowed to delete attributes, nor set or retrieved.

Pave the way for a future ECMAScript version
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 top of the script or method and cannot be placed in the middle of an if or a for statement.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.