It's time to start using the JavaScript strict mode.

Source: Internet
Author: User

ECMAScript5 introduces strict mode into Javascript to allow developers to select a "better" Javascript version, this version can be used in different ways to handle common and notorious errors. At the beginning, I was skeptical about the mode because only one browser (Firefox) supported the strict mode. Today, the latest versions of all mainstream browsers, including IE10 and Opera12, support strict mode. The time to use the strict mode is ripe.

What does it bring?

Strict mode brings many differences to the Javascript running mode. I divide them into two types: obvious (obvious) and subtle (subtle ). The subtle changes aim to solve the subtle problems, and I am not going to repeat them here. If you are interested in these details, please refer to the wonderful Dmitry Soshnikov article in ECMA-262-5 in Detail. Chapter 2. Strict Mode. I am more interested in introducing obvious changes: they are what you must know before you start to use strict patterns, and may bring you the most benefits.

Before introducing special features, remember that one of the goals of strict mode is to allow faster debugging of errors. The best way to help developers debug is to throw a corresponding error (throw errors when certain patterns occur) when a specific problem occurs ), instead of quietly failing or showing strange behavior (this is exactly what Javascript does today not do in strict mode ). In strict mode, the Code throws more error messages, which is a good thing, because it helps developers quickly notice problems that must be solved immediately.

Remove the with statement (Eliminates)

First, remove the with statement in strict mode. When a with statement appears in strict mode, it is considered invalid Javascript statements and throws syntax errors. Therefore, the first step to use the strict mode is to ensure that you are not using.

 
 
  1. // Syntax errors will occur in strict Mode
  2. With (location ){
  3. Alert (href );
  4. }

Prevents accidental globals)

The second point is that variables must be declared before being assigned values. In non-strict mode, a global variable with this name is automatically generated when an unspecified variable is assigned a value. This is one of the most common errors in Javascript. In strict mode, this will throw an error.

 
 
  1. // Throw an error in strict Mode
  2. (Function (){
  3. SomeUndeclaredVar = "foo ";
  4. }());

Cancel the forced conversion of this value (Eliminates this coercion)

Another important change is that when the value of this is null or undefined, it will not be forcibly converted to a global object. That is to say, this retains its original value, and may cause some code errors dependent on forced conversion. For example:

 
 
  1. Window. color = "red ";
  2. Function sayColor (){
  3. // In strict mode, this does not point to the window
  4. Alert (this. color );
  5. }
  6.  
  7. // In either of the following situations, an error is thrown in strict mode.
  8. SayColor ();
  9. SayColor. call (null );

Basically, this value must be assigned a value, otherwise the undefined value will be retained. This means that if the new keyword is missing when the constructor is called, the following error occurs:

 
 
  1. Function Person (name ){
  2. This. name = name;
  3. }
  4.  
  5. // Errors caused by strict Mode
  6. Var me = Person ("Nicolas ");

In this Code, the new keyword is missing when calling the Person constructor. The value of this is undefined. Because you cannot add attributes to undefined, this code throws an error. In non-strict mode, this is forcibly converted to a global object, so the name attribute can be correctly assigned as a global variable.

No duplicates)

When you perform a lot of encoding, you can easily define duplicate attributes in the object or define repeated parameter names for the function. In strict mode, both of these conditions will cause errors:

 
 
  1. // Error in strict mode-repeated Parameter
  2. Function doSomething (value1, value2, value1 ){
  3. // Code
  4. }
  5.  
  6. // Error in strict mode-duplicate attribute
  7. Var object = {
  8. Foo: "bar ",
  9. Foo: "baz"
  10. };

Both of these are syntax errors, which will be thrown before code execution.

Safer eval () (Safer eval ())

Eval () is not removed, but it has some changes in strict mode. The biggest change is that the variables and functions declared in the eval () statement are not created in the contained domain. For example:

 
 
  1. (Function (){
  2.  
  3. Eval ("var x = 10 ;");
  4.  
  5. // In non-strict mode, x is 10
  6. // In strict mode, x is not declared and an error is thrown.
  7. Alert (x );
  8.  
  9. }());

Any variable or function created by eval () remains in eval. However, you can pass the value by returning a value from eval:

 
 
  1. (Function (){
  2.  
  3. Var result = eval ("var x = 10, y = 20; x + y ");
  4.  
  5. // In both the strict and non-strict modes, the job can work normally for 30 times)
  6. Alert (result );
  7.  
  8. }());

Errors Caused by unchangeable (Errors for immutables)

ECMAScript 5 also introduces the ability to modify attribute features, such as setting an attribute to read-only or freezing the structure of the entire object (freezing an entire object's structure ). In non-strict mode, attempts to modify an unchangeable attribute will silently fail. You may have encountered such problems when using some native APIs. Strict mode ensures that an error is thrown whenever you try to modify the attributes of an object or object in an unacceptable way.

 
 
  1. Var person = {};
  2. Object. defineProperty (person, "name "{
  3. Writable: false,
  4. Value: "Nicolas"
  5. });
  6.  
  7. // In non-strict mode, the failure will be quietly failed. In strict mode, an error will be thrown.
  8. Person. name = "John ";

In this example, the name attribute is set to read-only. In non-strict mode, the name assignment will silently fail. In strict mode, an error will be thrown.

Note: If you are using the ECMAScript attribute (the ECMAScript attribute capabilities), I strongly recommend that you enable the strict mode. If you are changing the mutability of objects, you will encounter a bunch of errors, and they will be quietly taken away in non-strict mode.

How to use it?

Strict mode is easy to enable in modern browsers. You only need to add the following statement:

 
 
  1. "use strict"; 

Although this looks like a string that is not assigned a value to a variable, but it does indicate that the Javascript engine switches to the strict mode (browsers that do not support the strict mode simply read the string and continue to run as usual ). You can use it globally or in functions. Even so, you should never use it globally. Using this indicator globally means that all code in the same file is running in strict mode.

 
 
  1. // Do not do this
  2. "Use strict ";
  3.  
  4. Function doSomething (){
  5. // This will run in strict Mode
  6. }
  7.  
  8. Function doSomethingElse (){
  9. // This is also
  10. }

This does not seem to be a big problem, but in the world where our different scripts are stacked together (our world of aggressive script concatenation) will cause a lot of trouble. As long as a script contains this command globally, other serial scripts will also run in strict mode (which may lead to errors that you never expected ).

Therefore, it is best to use the strict mode only in the function, for example:

 
 
  1. Function doSomething (){
  2. "Use strict ";
  3. // Run in strict Mode
  4. }
  5.  
  6. Function doSomethingElse (){
  7. // Run in non-strict Mode
  8. }

If you want to apply the strict mode to multiple functions, you can use the following mode (immediately-invoked function expression (IIFE )):

 
 
  1. (function() {  
  2.  
  3.     "use strict";  
  4.  
  5.     function doSomething() {  
  6.         // this runs in strict mode  
  7.     }  
  8.  
  9.     function doSomethingElse() {  
  10.         // so does this  
  11.     }  
  12. }()); 

Conclusion

I strongly recommend that everyone start using the strict mode. Now there are enough browsers to support this mode, which will save you from hiding code errors. Make sure that you do not include the enable command globally, but you can use IIFEs frequently to apply the strict mode to any number of codes. In the beginning, you will encounter an error that you have never encountered -- this is normal. After switching to the strict mode, you need to do enough tests to ensure that you have held your code. You must not just throw "use strict" into your code and assume there will be no errors. At least, you should start to use this abnormal and useful language feature to write better code.

Original: http://zhoujunmiao.com /? P = 292

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.