Understanding the strict mode in javascript and the javascript Mode

Source: Internet
Author: User

Understanding the strict mode in javascript and the javascript Mode

I. What is a strict model?
The JavaScript code we usually write is generally run in the normal mode. In addition to the normal running mode, ECMAscript 5 adds the second running mode: "strict mode ). You can see the name. This mode allows JavaScript to run in a stricter environment.
Mainstream browsers, including IE 10, have supported it and many large projects have begun to embrace it. (Many projects on github use strict Mode)
Ii. enable strict Mode
Enable strict mode for the entire script
Put a specific statement "use strict" before all statements ";
Suppose there is a script reeoo. js, you can enable the strict mode as follows:

"use strict";var name = "Reeoo";console.log(name);

BUT there is a natural pitfall in this writing method. If we want to merge code, I want to put heigui. js:

heigui = "db";

Combined with reeoo. js, the two scripts are properly executed separately, and an error is returned when combined.
Uncaught ReferenceError: heigui is not defined (...)
Merging a script in strict mode and a script in non-strict mode may cause an error in the script code in non-strict mode. We recommend that the code be included in an immediate execution function.

(function(){ "use strict"; var name = "reeoo";})();(function(){ heigui = "db";})();

In this way, no error will be reported after merging.
Enable strict mode for a function
To enable the strict mode for a function, you must put the "use strict"; declaration before all the statements in the function body.

Function strictFun () {// function-level strict mode syntax 'use strict '; console. log (' I am a strictmode function! ');} Function normalFun () {console. log (' I am a mormal function! ');}

Strict debugging mode in Chrome
I have the following code:

'use strict'name = "reeoo";console.log(name)

Paste this Code directly to the Chrome console for execution. Normally, an error should be reported, but no error is reported,


Obviously, the var statement is not applicable to variables in strict mode, but why is there no error?
What is this? Does Chrome not support strict mode? Are you kidding me...
I searched the internet and found that the code in the Chrome console was running in eval. You cannot use the strict mode for the eval function (it should not be completely correct, but what did Chrome do, it is not known), indicating that the eval function can use the strict mode:

If you want to report an error in the strict mode in Chrome, you need to set an immediate execution function in the outer layer of the Code, or other similar measures.

(function(){ 'use strict' name = "reeoo"; console.log(name) })()

In this way, you can
Strict debugging mode for FireFox Code draft
Chrome requires us to package a closure to run the strict mode. In this case, is there any other way to directly run the code in the strict mode?
FireFox has a Code draft that can be run directly. The shortcut key SHIFT + F4

How strict is the strict mode?
Some important restrictions in strict Mode

1. Variable Declaration
An undeclared variable is not allowed.

"use strict";name = "reeoo";

Error (Code draft, the same below)
Exception: ReferenceError: assignment to undeclared variable name

2. Modify the value of the read-only attribute

"Use strict"; var testObj = Object. defineProperties ({}, {prop1: {value: 10, writable: false // a read-only property}, prop2: {get: function () {}}); testObj. prop1 = 20; // try to change the value of prop1 testObj. prop2 = 30; // try to change the value of prop2

In strict mode, an error is reported:
Uncaught TypeError: Cannot assign to read only property 'prop1' of # <Object>
In non-strict mode, the value cannot be assigned, and no error is reported.

3. modify attributes that cannot be extended
This is an object that adds an attribute to the extensible attribute and sets it to false.

"Use strict"; var testObj = new Object (); Object. preventExtensions (testObj); // objects processed by this method, without affecting the deletion and modification of the original objects. however, you cannot add new property members. testObj. name = "reeoo ";

Error in strict mode:
Uncaught TypeError: Can't add property name, object is not extensible
In non-strict mode, no error is reported, but testObj is not extended.
4. delete variables, functions, or parameters
Delete the property with the resumable attribute set to false.

"use strict";var testvar = 15,testObj={};function testFunc() {};delete testvar;delete testFunc;Object.defineProperty(testObj, "testvar", { value: 10, configurable: false });delete testObj.testvar;

Error:
Uncaught SyntaxError: Delete of an unqualified identifier in strict mode.

5. Define an attribute multiple times in an object text
Multiple definitions of an attribute are not allowed in strict mode.

"use strict";var testObj = { prop1: 10, prop2: 15, prop1: 20};

Error (node console)
Duplicate data property in object literal not allowed in strict mode
In normal mode, repeated variables declared later will overwrite the previously declared variables, and no error will be reported.
Note: this problem has been fixed in ECMAScript6.

6. Duplicate parameter names are not allowed in strict mode.

"use strict";function testFunc(param1, param1) { return 1;};

Error:
Uncaught SyntaxError: Duplicate parameter name not allowed in this context

7. Future reserved words of the identifier cannot be used. The identifier name will be retained in strict Mode
The following identifier (which is still not implemented in ES6) cannot be used in strict mode. Otherwise, an error is returned.
This is the end:
Uncaught SyntaxError: Unexpected strict mode reserved word

  • Implements
  • Interface
  • Package
  • Private
  • Protected
  • Public
  • Static
  • Yield

8. The octal numeric parameters and escape characters are not allowed in strict mode.

"use strict";var testoctal = 010;var testescape = \010;

Error:
Uncaught SyntaxError: Unexpected token ILLEGAL (...)
9. When the value of this is null or undefined, the value is not converted to a global object.
For example:

"use strict";function testFunc() { return this;}var testvar = testFunc();

In non-strict mode, the value of testvar is the Global Object window, but in strict mode, the value is undefined.

10. the string "eval" cannot be used as an identifier (variable or function name, parameter name, etc)

"use strict";var eval = "hehe";

Uncaught SyntaxError: Unexpected eval or arguments in strict mode

11. In strict mode, function declarations cannot be nested in statements or blocks.They can only be displayed at the top level or directly in the function body.

"use strict";var arr = [1, 2, 3, 4, 5];var index = null;for (index in arr) {  function myFunc() {};}

Node console:
SyntaxError: In strict mode code, functions can only be declared at top level or immediately within another function.
However, this restriction has been fixed in ES6.
12. eval usage is invalid in strict mode.
If a variable is declared in the eval function, the variable cannot be used outside the function.

"use strict";eval("var testvar = 10");console.log(testvars);

Uncaught ReferenceError: testvar is not defined

13. Invalid use of "arguments" in strict Mode
The string "arguments" cannot be used as an identifier (variable or function name, parameter name, etc ).

"use strict";var arguments = 1;

Uncaught SyntaxError: Unexpected eval or arguments in strict mode

This is similar to the limit of the above 10th.
14. The arguments in the function cannot change the value of the members of the arguments object.

"use strict";function testArgs(oneArg) {  arguments[0] = 20;}

In non-strict mode, you can change the value of the oneArg parameter by changing the value of arguments [0], so that the value of oneArg and arguments [0] is 20. In strict mode, changing the value of arguments [0] does not affect the value of oneArg, because the arguments object is only a local copy.
15. arguments. callee is not allowed.

"use strict";function my(testInt) {  if (testInt-- == 0)    return;  arguments.callee(testInt--);}my(100);

This is what happens when I use it:
Uncaught TypeError: 'caller', 'callee ', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for callto them
16.

"use strict";with (Math){  x = cos(3);  y = tan(7);}

Uncaught SyntaxError: Strict mode code may not include a with statement
Why strict mode?
Since there are so many restrictions on this mode, why should I use it? Is it so cool? Of course, 8 is,
JavaScript, as a scripting language used in browsers at the beginning, has a very good fault tolerance. Even if your code is not written standards, it will not report errors, but sometimes it will become a code hazard. After the strict mode is enabled, some unreasonable and not rigorous syntaxes of JavaScript will be controlled, so that you can write JavaScript code more rigorously and become a better programmer. The strict mode is the product of the ES5 era. ES2015 is already on the road to popularization. It is time to use the strict mode!

Articles you may be interested in:
  • Stricter equality of JavaScript [translation]
  • JavaScript start point (deep understanding of strict Mode)
  • Strict mode of Javascript
  • Reasons for disabling the With statement in strict JavaScript Mode
  • Equivalent and strictly equal symbols of Javascript learning notes
  • Strict Mode)
  • Learn the strict javascript Mode
  • Detailed description of the strict JavaScript 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.