JavaScript Strict mode and its use __java

Source: Internet
Author: User
Tags aliyun
1 Preface

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 support rigorous patterns (including IE10,OPERA12 and ANDROID4,IOS5) in their latest version, and it's time to start using strict mode.

The "use strict" directive is added to JavaScript 1.8.5 (ECMASCRIPT5). It is not a statement, but is a literal expression that is ignored in older versions of JavaScript. The purpose of "use strict" is to specify that code executes under strict conditions. In strict mode you cannot use undeclared variables. 2 changes brought about by strict patterns

Strict mode by adding "use strict" to the head of the script or function; An expression to declare. You can view them through the F12 of the browser.

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, not to be covered here; If you are interested, please read the wonderful document written by 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.

One feature of the JavaScript language is that it allows for "dynamic binding," where certain properties and methods belong to exactly one object, not at compile time, but at runtime (runtime). Strict mode has some restrictions on dynamic binding. in some cases, only static bindings are allowed, that is, which object the attribute and method belong to, determined at compile time. based on the grammatical features above, there will be some special changes when using strict mode. 1. You must use the var keyword the first time you assign a value to a variable

In normal mode, a global variable with the same name is automatically created when a value is assigned to 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.

"Use strict";
x = 3.14;       Error (x not defined) 
     
     
      
      
     
     

When you define a variable inside a function, you also need to use the var keyword.

"Use strict";
MyFunction (); 
function MyFunction () {
   y = 3.14;   Error (y not defined)
}

     
     
      
      
     
     
2. This in 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:

Window.color = "Red";
function Saycolor () {
 alert (this.color);
}
In the strict mode will be an error, if not in strict mode is prompted "Red"
saycolor ();
Error in strict mode, if not in strict mode, prompt "Red"
saycolor.call (NULL);

     
     
      
      
     
     

The following contrast code clearly reflects how the undefined this keyword points to differences in both normal and strict mode.


function f () {return
!this; 
//returns false because "this" points to a global object, "!this" is false
function f () { 
"use strict";
return!this; 
//Returns True because the value of undefined this is undefined in strict mode, so "!this" is true.

     
     
      
      
     
     

In strict mode, this will remain undefined until it is explicitly assigned, which means that when a constructor executes, it throws an exception if there is no explicit new keyword.

function person (name) {
' use strict ';
 this.name = name;
var me = person ("Nicholas"); Error, this is not defined 

     
     
      
      
     
     

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 to set a Name property for the window global variable with the property value "Nicholas". 3. Prevent duplicate names

When writing a large number of code, object properties and function parameters are easily inadvertently set to a duplicate name, strict mode in this case will explicitly throw errors.


function dosomething (value1, value2, value1) {  //duplicate variable name, in strict mode will be the error
    "use strict"
 /...
}

     
     
      
      
     
     

For the duplication of object attribute names, the processing strategies of different JS operating environments are different. The test code is as follows:

var fn = function () {
    ' use strict ';
     var obj =  { 
        a:1, 
        a:2       //Because there are more declared attributes, the attributes added later are accidentally duplicated with existing properties  
     };
     return obj
};
FN ();

     
     
      
      
     
     

At that time, I tested the program in the PC's Chrome, ran no problem, and tested it on the Android machine, and no problem. But in the iphone but the error, resulting in the page is not normal rendering. Let's look at the implementation of this code in each of the running environments: Chrome Safari Firefox Nodejs

from the above experimental results can be seen, even in strict mode, the various operating environment for some of the details of the processing is not the same. In the strict mode of Safari and Nodejs, object literals prohibit duplicate attribute declarations, while Chrome and Firefox do not have this limitation. So even if the code running in strict mode is not 100% insured, it is necessary to do more testing. For strict mode to help prevent the function parameter names and object property names Repeat this point, the different JS operating environment effect is different. 4. Create an eval () scope to make eval () more secure

Although the Eval () statement has not been removed in strict mode, it is still improved in strict mode. The biggest change is that the variables and function declarations in eval () can only be used within the Eval statement.

In normal mode, the JavaScript language has two variable scopes (SCOPE): global scope and function scope. The rigorous model creates a third scope: the eval scope. In normal mode, the scope of the Eval statement depends on whether it is in the global scope or in the function scope. In strict mode, the Eval statement itself is a scope that can no longer generate a global variable, and its generated variables can only be used within the eval. For example:

(function () {
 eval ("var x =;");
 In non-strict mode, normal display 10, in strict mode because x is not defined and throw an exception,
 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:

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

     
     
      
      
     
     
5. Throw an exception when modifying a read-only property

ECMASCRIPT5 also introduces the ability to set the specific properties of an object to read-only syntax, 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.

function 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. 6. Prohibit use with statement

Because the WITH statement cannot determine at compile time which object the attribute belongs to. The WITH statement is removed in strict mode, and the code that contains 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.

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

     
     
      
      
     
     
3 How to use strict mode.

Strict mode uses flags to place "use strict" on the first line of the script file, the entire script will run in "strict mode." If the line statement is not in the first row, it is invalid and the entire script runs in normal mode.

"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.

Please do not use
 "using 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:

function dosomething () {
 "use strict";
 The code in this function will run in strict mode
} function
Dosomethingelse () {
 //The code will not run in strict mode
}

     
     
      
      
     
     

If you want the strict mode to open in more than one function, use the immediate execution function expression

(function () {
    ' use strict ' function
    dosomething () {
        //) runs in strict mode
        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";
    }
    function Dosomethingelse () {//
         the same functions run in strict mode
         //In strict mode the following JavaScript code throws errors with
         (location) {
            alert (HREF);}}
());

     
     
      
      
     
     
4 Conclusion

Programmers using JS should always have JavaScript strict mode enabled, which can help you find errors that you haven't noticed in your code. Do not enable it in the global environment, but you can use the immediate execution function expression as much as possible to apply the strict pattern to multiple function scopes. 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 have tested 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.

Summary statistics for strict mode support for each browser: Click here reference materials: http://www.nczonline.net/blog/2012/03/13/its-time-to-start-using-javascript-strict-mode/https:// Yq.aliyun.com/articles/63539?spm=5176.100240.searchblog.84.3cr1qs http://blog.csdn.net/xingqiliudehuanghun/ article/details/46369289 Https://yq.aliyun.com/articles/45363?spm=5176.100240.searchblog.8.7nvmCP

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.