In-depth understanding of Strict Mode and criptstrict in javascript

Source: Internet
Author: User

In-depth understanding of Strict Mode and criptstrict in javascript

The strict mode introduced in ECMAScript5 allows the JavaScript runtime environment to process the most common and difficult-to-discover errors in the development process differently from the current one, to make developers have a "better" JavaScript language. For a long time, I had doubts about the strict mode because only Firefox supports the strict mode. However, today, all mainstream browsers support strict mode (including IE10, Opera12, Android4, and IOS5) in their latest versions.

What is the role of strict mode?

The strict mode introduces a lot of changes to JavaScript, and I divide them into two types (obvious and subtle ). The goal of minor improvements is to fix some of the details in JavaScript. I will not go into these details here. If you are interested, please read the wonderful ECMA-262-5 in Detail Chapter 2 Strict Mode written by Dmitry Soshnikov. Here I will mainly introduce the significant changes introduced by the strict mode, the concepts you should know before using the strict mode and the biggest changes that will help you.

Before learning specific features, remember that the goal of strict mode is to allow faster and more convenient debugging. It is better to explicitly throw an error when a running environment discovers a problem than to silently fail or behave in a strange way (JavaScript running environment with strict mode not enabled. Strict mode throws more errors, but this is a good thing, because these errors will arouse your attention and fix many potential problems that were hard to be found before.

Remove WITH keywords

First, remove the with statement in strict mode. The code containing the with statement throws an exception in strict mode. So the first step to use the strict mode: Make sure that your code does not use.

Copy codeThe Code is as follows:
// In strict mode, the following JavaScript code throws an error
With (location ){
Alert (href );
}

Avoid accidental assignment of global variables

Second, local variables must be affirmed before being assigned values. Before strict mode is enabled, a global variable with the same name is automatically created when copying an unstated local variable. This is one of the most common errors in the Javacript program. explicit exceptions are thrown when you try this operation in strict mode.

Copy codeThe Code is as follows:
// Exception thrown in strict Mode
(Function (){
SomeUndeclaredVar = "foo ";
}());

THIS in the function no longer points to global by default

Another important change in strict mode is that this in the function is not defined or is null or undefined. this does not point to the global environment by default ). This will cause code execution errors for the default this behavior in some dependent functions, such:

Copy codeThe Code is as follows:
Window. color = "red ";
Function sayColor (){
Alert (this. color );
}
// An error is reported in strict mode. If not in strict mode, the system prompts "red"
SayColor ();
// An error is reported in strict mode. If not in strict mode, the system prompts "red"
SayColor. call (null );

This will remain undefined until it is assigned a value, which means that when a constructor is executing, if no new keyword is specified before, an exception will be thrown.

Copy codeThe Code is as follows:
Function Person (name ){
This. name = name;
}
// An error is reported in strict mode.
Var me = Person ("Nicolas ");

In the above Code, because the Person constructor does not have a new one, this in the function will be reserved as undefined. Because you cannot set attributes for undefined, the above Code will throw an error. In a non-strict mode environment, if this is not copied, it will point to the window global variable by default. The running result will accidentally set the name attribute for the window global variable.

Prevent duplicate names

When writing a large amount of code, object attributes and function parameters are easily accidentally set to a duplicate name. In this case, an explicit error is thrown.

Copy codeThe Code is as follows:
// Duplicate variable names. An error is reported in strict mode.
Function doSomething (value1, value2, value1 ){
// Code
}
// Duplicate Object Property names. In strict mode, an error is returned:
Var object = {
Foo: "bar ",
Foo: "baz"
};

The above code is regarded as a syntax error in strict mode, and you will be prompted before execution.

Secure EVAL ()

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

Copy codeThe 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 eval () execution are retained in eval. However, you can obtain the execution result in eval () from the return value of the eval () statement, for example:

Copy codeThe Code is as follows:
(Function (){
Var result = eval ("var x = 10, y = 20; x + y ");
// The remaining statements can be correctly run in strict or non-strict mode. (resulst is 30)
Alert (result );
}());

An exception is thrown when the read-only attribute is modified.

ECMAScript5 also introduces the ability to set specific properties of an object to read-only, or make the entire object unmodifiable. However, in non-strict mode, an attempt to modify a read-only attribute will only fail without silence. You may encounter this situation when dealing with some browser native APIs. Strict mode will explicitly throw an exception in this case, reminding you that modifying this attribute is not allowed.

Copy codeThe Code is as follows:
Var person = {};
Object. defineProperty (person, "name "{
Writable: false,
Value: "Nicolas"
});
// Silence fails in non-strict mode, and an exception is thrown in strict mode.
Person. name = "John ";

In the preceding example, the name attribute is set to read-only. If you modify the name attribute in non-strict mode, no error is returned, but the modification will not succeed. However, the strict mode explicitly throws an exception.

NOTE: we strongly recommend that you use any ECMAScript attribute feature to enable strict mode at regular intervals.

How to use it?

It is very easy to enable the strict mode in modern browsers. You only need to show the following commands in JavaScript code.

"Use strict ";
 

Although it seems that the above Code is only a string that has not been assigned a variable, it actually plays a role in instructing the JavaScript engine to switch to the strict mode (browsers that do not support the strict mode will ignore the above Code, will not affect subsequent execution ). Although you can apply this command to a global function or a function, you need to remind me not to enable the strict mode in the global environment.

Copy codeThe Code is as follows:
// Do not use this method
"Use strict ";
Function doSomething (){
// This part of the code runs in strict Mode
}
Function doSomethingElse (){
// This part of the code will also run in strict Mode
}

 
Although the above Code does not seem to be a big problem. However, when you are not responsible for maintaining all the Code introduced in the page, using the strict mode will lead to problems caused by third-party code not preparing for the strict mode.

Therefore, it is best to apply commands that enable strict mode to functions, for example:

Copy codeThe 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 does not run in strict Mode
}

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

Copy codeThe 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 the JavaScript strict mode from now on, which can help you discover errors that have not been noticed in the code. Do not enable it in the global environment, but you can use IIFE (Execute function expressions immediately) as much as possible to apply the strict mode to multiple function ranges. At the beginning, you will encounter an error message that you have never encountered before. This is normal. When strict mode is enabled, make sure that you have tested the supported browsers to discover new potential problems. Do not simply add a line of "use strict" in the code to assume that the remaining code works properly. Finally, write better code in strict mode.

Note:
Each browser provides a summary of the strict mode support.
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. In normal mode, this is always an object.
2. Fun. caller and fun. arguments are attributes that cannot be deleted or set or retrieved.
3. Arguments. caller cannot be deleted or set or retrieved.

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

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.