Home Web Front-end JS Tutorial Detailed introduction to strict mode of Javascript_javascript skills

Detailed introduction to strict mode of Javascript_javascript skills

May 16, 2016 pm 04:46 PM
javascript strict mode

"Strict mode" is a new syntax defined by ECMA-262 Edition 5, which means that strict Javascript syntax must be used for execution. Some commonly used writing methods in the past will throw SyntaxError exceptions, such as:
1. There is no var declaration before the variable
2. Use octal syntax: var n = 023 and var s = "

1. Why use "strict mode"


The main purposes of establishing "strict mode" are as follows:

1. Eliminate some unreasonable and imprecise aspects of Javascript syntax and reduce some weird behaviors;
2. Eliminate some unsafe aspects of code running and ensure the safety of code running;
3. Improve Compiler efficiency and increased running speed;
4. 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, already support it, and many large projects have begun to fully embrace it.
On the other hand, the same code may have different running results in "strict mode"; some statements that can run in "normal mode" will not run in "strict mode". Mastering these contents will help you understand Javascript in more detail and make you a better programmer.

This article will introduce "strict mode" in detail.


2. Declare "strict mode"

Declaring "strict mode" is very simple with just one statement:

Copy the code

The code is as follows:

"use strict";


Note: Older versions of browsers will treat it as a line of ordinary strings and ignore it.

3. The position and context of declaring "strict mode" "Strict mode" mainly affects the scope in which it is located. If used in a function, it will not make the global scope and other unused functions become "strict mode". That is, the scope of a strict mode declaration depends on its context. If strict mode is declared in the global context (outside the scope of a function), all code in the program is in strict mode. If you declare strict mode in a function, all code within the function is in strict mode. For example, in the following example, all code is in strict mode, and a variable declaration outside a function results in a syntax error: "Variable is not defined in strict mode." "Strict mode" has two calling methods, suitable for different situations.
1. For the entire script file

Put "use strict" on the first line of the script file, and the entire script will run in "strict mode". If this line of statement is not the first line, it is invalid and the entire script runs in "normal mode". This needs special attention if code files from different modes are merged into one file.

(Strictly speaking, as long as it is not preceded by a statement that produces actual operation results, "use strict" does not need to be on the first line, such as directly following an empty semicolon.)

Copy code

The code is as follows:


<script><p>"use strict"; </p> <div class="codetitle">console.log("This is strict mode.");<span></script> <script></u>console.log("This is normal mode.");</a></script>

The above code indicates that there are two pieces of Javascript code in a web page. The former script tag is in strict mode, but the latter one is not.


2. For a single function


Put "use strict" on the first line of the function body, and the entire function will run in "strict mode".

Copy code

The code is as follows:

function strict(){
"use strict" ;

return "This is strict mode.";}function notStrict() {return "This is normal mode.";}

3. Alternative way of writing script files

Because the first calling method is not conducive to file merging, a better approach is to borrow the second method and The entire script file is placed in an anonymous function that is executed immediately.
Copy code The code is as follows:

(function (){

"use strict";
// some code here

})();

4. Syntax and behavior changes in "strict mode"

"Strict mode" has made some changes to the syntax and behavior of Javascript.

1. Explicit declaration of global variables

In normal mode, when we use variables, we do not have to declare them with var first (explicit declaration), but in Strict Mode, variables must be declared with var before they can be used, otherwise it will An error occurred.

Copy code The code is as follows:

"use strict";
v = 1; // Error reported, v is not declared
for(i = 0; i < 2; i ) { // Error reported, i is not declared
}

Therefore, in strict mode, variables must Declare it with the var command first, and then use it.

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

Strict mode imposes some restrictions on dynamic binding. In some cases, only static binding is allowed. In other words, which object the properties and methods belong to is determined during the compilation stage. This will help improve compilation efficiency, make the code easier to read, and cause fewer surprises.

Specifically, it involves the following aspects.

(1) It is forbidden to use the with statement

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

Copy code The code is as follows:

"use strict";
var v = 1 ;
with (o){ // Syntax error
v = 2;
}

(2) Create eval scope

In normal mode, the Javascript language has two variable scopes: global scope and function scope. Strict mode creates a third scope: eval scope.
In normal mode, the scope of the eval statement depends on whether it is in the global scope or the 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.

Copy code The code is as follows:

"use strict";
var x = 2 ;
console.info(eval("var x = 5; x")); // 5
console.info(x); // 2

3. Enhanced security measures

(1) Prohibit this keyword from pointing to the global object

Copy code The code is as follows:

function f(){
return !this;
}
// Return false, because "this" points to the global object, "!this" is false
function f (){
"use strict";
return !this;
}

// Return 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 will no longer point to the global object, but an error will be reported.
Copy code The code is as follows:

function f(){

"use strict";
this.a = 1;
};
f();// Error, this is undefined


In a normal function call f(), the value of this will point to the global object. In strict mode, the value of this will point to undefined. When the function is called through call and apply, if the thisvalue parameter passed in is a For primitive values ​​(strings, numbers, Boolean values) except null and undefined, the value of this will become the packaging object corresponding to that primitive value. If the value of the thisvalue parameter is undefined or null, the value of this will point to the global object. In strict mode, the value of this is the value of the thisvalue parameter without any type conversion.

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

Copy the code The code is as follows:

function f1(){

"use strict";
f1.caller; // Error reporting
f1.arguments; // Error reporting
}
f1();

4. Deletion of variables is prohibited

Variables cannot be deleted in strict mode. Only object attributes with configurable set to true can be deleted.

Copy code The code is as follows:

"use strict";
var x;
delete x; // Syntax error
var o = Object.create(null, 'x', {
value: 1,
configurable: true
});
delete o.x ; // Deletion successful

5. Explicit error reporting

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

Copy code The code is as follows:

"use strict";
var o = { };
Object.defineProperty(o, "v", { value: 1, writable: false });
o.v = 2; // Error reporting

In strict mode, use getter for a If the attribute read by the method is assigned a value, an error will be reported.
Copy code The code is as follows:

"use strict";
var o = {
get v() { return 1; }
};
o.v = 2; // Error report

In strict mode, adding new attributes to objects that are prohibited from expansion will report an error.
Copy code The code is as follows:

"use strict";
var o = { };
Object.preventExtensions(o);
o.v = 1; // Error reporting

In strict mode, deleting an attribute that cannot be deleted will report an error.
Copy code The code is as follows:

"use strict";
delete Object.prototype ; // Report error

6. Duplicate name error

Strict mode has added some new syntax errors.

(1) Objects cannot have attributes with duplicate names

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

Copy code The code is as follows:

"use strict";
var o = {
p: 1,
p: 2
}; // Syntax error

(2) Functions cannot have parameters with duplicate names

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

Copy code The code is as follows:

"use strict";
function f(a , a, b) { // Syntax error
return ;
}

7. Octal notation is prohibited

In normal mode, if the first digit of an integer is 0, it means it is an octal number. For example, 0100 is equal to 64 in decimal. Strict mode prohibits this representation, the first bit of the integer is 0, and an error will be reported.

Copy code The code is as follows:

"use strict";
var n = 0100 ; // Syntax error
8. 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

Copy code The code is as follows:

"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 parameter changes

Copy code The code is as follows:

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) It is forbidden to use arguments.callee

This means that you cannot call itself inside an anonymous function.

Copy code The code is as follows:

"use strict";
var f = function () { return arguments.callee; };
f(); // Report error

9. Functions must be declared at the top level

New versions of Javascript will introduce "block-level scope" in the future. In order to keep in line with the new version, strict mode only allows functions to be declared in the global scope or the top level of the function scope. That is, it is not allowed to declare functions within a non-function code block.

Copy code The code is as follows:

"use strict";
if (true) {
function f() { } // Syntax error
}
for (var i = 0; i < 5; i ) {
function f2() { } // Syntax error
}


10. Reserved words

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

Copy code The code is as follows:

function package(protected) { // Syntax error
"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 the const reserved words added by major browsers, cannot be used as variable names.
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles