Javascript strict mode "strict mode"

http://www.bug315.com/article/518.htm

 

In addition to the normal operation mode of JavaScript, ECMAscript 5 adds a second operation mode called "strict mode" (strict mode). As the name suggests, this mode makes Javascript run under stricter conditions. The purpose of establishing "strict mode" is mainly for the following reasons:

(1) Eliminate some unreasonable and imprecise aspects of Javascript syntax and reduce some weird behaviors;

(2) Eliminate some insecurities of code operation and ensure the safety of code operation;

(3) Improve the efficiency of the compiler and increase the running speed;

(4) To pave the way for new versions of Javascript in the future.

 

"Strict mode" reflects the more reasonable, safer and more rigorous development direction of Javascript. Mainstream browsers, including IE 10, have already supported it, and many large projects have begun to fully embrace it. On the other hand, the same code may run differently in "strict mode"; some statements that can run in "normal mode" will not run in "strict mode".

 

enter strict mode

Use the following statement to enter the "strict mode" flag, as follows:

# mark as strict mode

"use strict";

Older browsers treat it as a normal string and ignore it.

 

How to use strict mode

"Strict mode" can be used in several ways, suitable for different situations. They are as follows:

 

entire script file

Put "use strict" on the first line of your script file and the entire script will run in "strict mode". If this line of statements is not on the first line, it has no effect (the whole script runs in "normal mode"). Strictly speaking, "use strict" may not be on the first line, as long as it is not preceded by a statement that produces the actual running result, such as directly following an empty semicolon. Examples are as follows:

<script type="text/javascript">

    "use strict";

    console.log("This is strict mode.");

</script>

 

<script type="text/javascript">

    console.log("This is normal mode.");

</script>

The above code indicates that there are two pieces of Javascript code in a web page in turn. The former script tag is strict mode, the latter is not. Because the above method is not conducive to file merging, it is better to use an anonymous method to put the entire script file in an anonymous function that is executed immediately. as follows:

(function (){

    "use strict";

    // some code here

})();

single function

Put "use strict" on the first line of the function body, and the entire function runs in "strict mode". The example code is as follows:

// strict mode

function strict(){

    "use strict";

    return "This is strict mode.";    

}

 

// normal mode

function notStrict() {

    return "This is normal mode.";

}

 

 

strict mode syntax

Strict mode makes some changes to the syntax and behavior of Javascript. The following will be introduced separately:

 

Explicit declaration of global variables

In normal mode, if a variable is assigned a value without a declaration, it defaults to a global variable. Strict mode prohibits this usage, global variables must be declared explicitly. Examples are as follows:

"use strict";

my = 1; // error, my is not declared

for( i = 0; i < 100; i++ ) {

    // error, i is not declared

}

Therefore, in strict mode, variables must be declared with the var command before they are used.

 

static binding

A feature of the Javascript language is that it allows "dynamic binding", that is, which object certain properties and methods belong to is not determined at compile time, but at runtime (runtime). However, strict mode places some restrictions on dynamic binding. In some cases, only static binding is allowed. That is to say, which object the properties and methods belong to is determined at the compilation stage. Doing so is beneficial to the improvement of compilation efficiency, and also makes the code easier to read and less unexpected. Specifically, it involves the following aspects.

 

(1) Prohibit the use of the with statement

 

Because the with statement cannot determine at compile time which object the property belongs to.

"use strict";

var userObj = {};

var age = 1;

with (userObj) {

    // Grammatical errors

    age = 2;

}

(2) eval scope

 

In normal mode, the Javascript language has two variable scopes: the global scope and the local scope. Strict mode creates a third type of scope: the eval scope. In normal mode, the scope of an eval statement depends on whether it is in global scope or function scope. In strict mode, the eval statement itself is a scope and can no longer generate global variables. The variables it generates can only be used inside eval. as follows:

"use strict";

var x = 2;

console.info(eval("var x = 5; x")); // result: x=5

console.info(x); // result: x=2

 

 

Enhanced Security Measures

(1) The this keyword is prohibited from pointing to the global object

function f() {

  return !this;

// returns false, because "this" points to the global object, "!this" is false

function f() { 

  "use strict";

  return !this;

// Returns true, because in strict mode, the value of this is undefined, so "!this" is true.

// Therefore, when using the constructor, if you forget to add new, this no longer points to the global object, but an error is reported.

function f() {

  "use strict";

  this.a = 1;

};

f(); // error, this is undefined

(2) It is forbidden to traverse the call stack inside the function

function f1(){

  "use strict";

  f1.caller; // error

  f1.arguments; // error

}

f1 ();

 

 

Forbid deletion of variables

Variables cannot be deleted in strict mode. Only object properties with configurable set to true can be deleted. Examples are as follows:

"use strict";

var x;

delete x; // syntax error

var o = Object.create(null, {'x': {

  value: 1,

  configurable: true

}});

delete ox; // delete successfully

 

 

explicit error

In normal mode, assigning a read-only property of an object will not report an error, but will simply fail silently. In strict mode, an error will be reported. as follows:

"use strict";

var o = {};

Object.defineProperty(o, "v", {

    value : 1,

    writable : false

});

ov = 2; // report an error

In strict mode, assigning a value to a property read using the getter method will result in an error. as follows:

"use strict";

var o = {

    get v() {

        return 1;

    }

};

ov = 2; // report an error

In strict mode, adding a new property to an object whose extension is prohibited will result in an error. as follows:

"use strict";

var o = {};

Object.preventExtensions(o);

ov = 1; // report an error

In strict mode, deleting an undeletable property will result in an error. as follows:

"use strict";

delete Object.prototype; // error

 

duplicate name error

Strict mode adds some syntax errors.

 

(1) Objects cannot have properties with the same name

In normal mode, if an object has multiple properties with the same name, the property assigned last will overwrite the previous value. In strict mode, this is a syntax error.

"use strict";

var o = {

    p : 1,

    p : 2

}; // Grammatical errors

(2) The function cannot have parameters with the same name

 

In normal mode, if a function has multiple parameters with the same name, they can be read with arguments[i]. In strict mode, this is a syntax error.

"use strict";

function f(a, a, b) { // syntax error

    return ;

}

 

Forbid octal notation

In normal mode, if the first digit of an integer is 0, it means that this is an octal number, for example, 0100 is equal to 64 in decimal. Strict mode forbids this notation, and an integer with a 0 in the first digit will report an error. Examples are as follows:

"use strict";

var n = 0100; // syntax error

 

 

Limitations of arguments object

arguments is the parameter object of the function, and strict mode restricts its use.

(1) Assignment to arguments is not allowed

"use strict";

arguments++; // syntax error

var obj = { set p(arguments) { } }; // syntax error

try { } catch (arguments) { } // syntax error

function arguments() { } // syntax error

var f = new Function("arguments", "'use strict'; return 17;"); // syntax error

(2) arguments no longer track changes in parameters

function f(a) {

    a = 2;

    return [a, arguments[0]];

}

f(1); // normal mode is [2,2]

 

function f(a) {

    "use strict";

    a = 2;

    return [a, arguments[0]];

}

f(1); // strict mode is [2,1]

 

(3) Prohibit the use of arguments.callee

This means, you can't call itself inside an anonymous function. Examples are as follows:

"use strict";

var f = function () {

    return arguments.callee;

};

f(); // error

 

 

Functions must be declared at the top level

Future versions of Javascript will introduce "block scopes". In keeping with newer versions, strict mode only allows functions to be declared at the top level of the global scope or function scope. That is, functions are not allowed to be declared inside code blocks that are not functions. Examples are as follows:

"use strict";

if (true) {

    function f() {

        // Grammatical errors

    }

}

for (var i = 0; i < 5; i++) {

    function f2() {

        // Grammatical errors

    }

}

 

 

reserved word

In order to transition to new versions of Javascript in the future, strict mode adds some reserved words: implements, interface, let, package, private, protected, public, static, yield. Using these words as variable names and function names will result in an error. Examples are as follows:

// Syntax error (because the function name package is a reserved word)

function package(protected) {

    "use strict";

    var implements; // syntax error

}

In addition, the fifth version of ECMAscript itself also stipulates other reserved words (class, enum, export, extends, import, super), as well as const reserved words added by major browsers, which cannot be used as variable names. For more information on ECMAscript 5th Edition, see the ECMAScript5 Specification.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326615031&siteId=291194637