JavaScript (deep understanding in strict mode) _ basic knowledge

Source: Internet
Author: User
Strict mode (StrictMode) is a new feature of ECMAScript5. Currently, the latest versions of all mainstream browsers, including IE10 and Opera12, support strict mode. If you are interested, please understand, I hope this article will help you. Strict Mode is a new feature of ECMAScript5. Although ECMAScript5 can be backward compatible with ECMAScript3, if strict mode is used, ECMAScript5's ECMAScript3 syntax function "not recommended" will be fully written. If it appears, a row will be thrown. The purpose of introducing Strict Mode is to allow developers to select a "better" Javascript version, which can handle common and notorious errors in different ways. The latest versions of all mainstream browsers, including IE10 and Opera12, support strict mode. Most information about the strict mode can be found on page 223rd of ES5 specification [PDF.

How to enable strict Mode
Strict mode can be used globally or within a function range. To enable strict mode globally, you only need to use the code in the first line of the program:

The Code is as follows:


'Use strict ';


To enable the strict mode inside the function, you only need to use the code in the first line of the function body:

The Code is as follows:


Function imStrict (){
'Use strict ';
//... Other code...
}


The statement that enables strict mode is just a common string "use strict" without any new syntax. This means that it will not have any negative impact on the old browser, so you can use it boldly.

One practical application of enabling the strict mode inside a function is to define the entire Javascript class library inside the function of the strict mode, so that the external code is not affected:

The Code is as follows:


(Function (){
"Use strict ";
// Define your library strictly...
})();


What does the strict mode bring?
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 ). Code in strict mode throws more error messages, which is a good thing because it helps developers quickly notice issues 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.

The Code is as follows:


// Syntax errors will occur in strict Mode
With (location ){
Alert (href );
}


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.

The Code is as follows:


// Throw an error in strict Mode
(Function (){
SomeUndeclaredVar = "foo ";
}());


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:

The Code is as follows:


Window. color = "red ";
Function sayColor (){
// In strict mode, this does not point to the window
Alert (this. color );
}
// In either of the following situations, an error is thrown in strict mode.
SayColor ();
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:

The Code is as follows:


FunctionPerson (name ){
This. name = name;
}
// Errors caused by strict Mode
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:

The Code is as follows:


// Error in strict mode-repeated Parameter
Function doSomething (value1, value2, value1 ){
// Code
}
// Error in strict mode-duplicate attribute
Var object = {
Foo: "bar ",
Foo: "baz"
};


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:

The Code is as follows:


(Function (){
Eval ("var x = 10 ;");
// In non-strict mode, x is 10
// In strict mode, x is not declared and an error is thrown.
Alert (x );
}());


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

The Code is as follows:


(Function (){
Var result = eval ("var x = 10, y = 20; x + y ");
// Works properly in both strict and non-strict modes (get 30)
Alert (result );
}());


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.

The Code is as follows:


Var person = {};
Object. defineProperty (person, "name "{
Writable: false,
Value: "Nicolas"
});
// In non-strict mode, the failure will be quietly failed. In strict mode, an error will be thrown.
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 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.

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.