search
HomeWeb Front-endJS TutorialDetailed explanation of Javascript strict mode

Detailed explanation of Javascript strict mode

Aug 31, 2020 pm 05:18 PM
javascriptstrict mode

Detailed explanation of Javascript strict mode

【Related learning recommendations: javascript learning tutorial

In addition to the normal running mode, ECMAscript 5 adds a second running mode: "strict mode". As the name suggests, this mode makes Javascript run under stricter conditions.

The purpose of establishing "strict mode" is mainly as follows:

- Eliminate some unreasonable and imprecise aspects of Javascript syntax and reduce some weird behaviors;

- Eliminate some insecurities in code running and ensure the safety of code running;

- Improve compiler efficiency and increase running speed;

- Prepare for future new versions of Javascript Make good preparations.

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

On the other hand, the same code may have different running results in "strict mode"; some statements that can be run in "normal mode" will not be able to be run in "strict mode" run. 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. Entry flag

The sign to enter "strict mode" is the following line:

  "use strict";

Older versions of browsers will It is treated as an ordinary string and ignored.

3. How to call

There are two calling methods for "strict mode", which are suitable for different occasions.

3.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 operating results, "use strict" does not need to be on the first line, such as directly following an empty semicolon.)

<script>
"use strict";
console.log("这是严格模式。");
</script>

<script>
console.log("这是正常模式。");kly, it&#39;s almost 2 years ago now. I can admit it now - I run it on my school&#39;s network that has about 50 computers.
</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.

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

function strict(){
"use strict";
return "这是严格模式。";
}

function notStrict() {
return "这是正常模式。";
}

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

(function (){

"use strict";

// some code here

})();

4. Syntax and behavior changes

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

4.1 Explicit declaration of global variables

In normal mode, if a variable is assigned a value without being declared, the default is a global variable. Strict mode prohibits this usage and global variables must be declared explicitly.

"use strict";

v = 1; // 报错,v未声明

for(i = 0; i < 2; i++) { // 报错,i未声明
}

Therefore, in strict mode, variables must be declared with the var command before use.

4.2 Static Binding

One of the characteristics of the Javascript language is that it allows "dynamic binding", that is, which object some properties and methods belong to, not in which object they belong to. It is determined at compile time, but at runtime.

Strict mode places 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.

"use strict";

var v = 1;

with (o){ // 语法错误
v = 2;
}

(2) Create eval scope

In normal mode, the Javascript language has two variable scopes (scope): 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.

"use strict";

var x = 2;

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

console.info(x); // 2

4.3 Enhanced security measures

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

function f(){
return !this;
}
// 返回false,因为"this"指向全局对象,"!this"就是false

function f(){
"use strict";
return !this;
}
// 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。

Therefore, use When constructing a function, if you forget to add new, this will no longer point to the global object, but an error will be reported.

function f(){

"use strict";

this.a = 1;

};

f();// 报错,this未定义

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

function f1(){

"use strict";

f1.caller; // 报错

f1.arguments; // 报错

}

f1();

4.4 It is forbidden to delete variables

Not possible in strict mode Delete variables. Only object properties with configurable set to true can be deleted.

"use strict";

var x;

delete x; // 语法错误

var o = Object.create(null, {&#39;x&#39;: {
value: 1,
configurable: true
}});

delete o.x; // 删除成功

4.5 Explicit error reporting

正常模式下,对一个对象的只读属性进行赋值,不会报错,只会默默地失败。严格模式下,将报错。

"use strict";

var o = {};

Object.defineProperty(o, "v", { value: 1, writable: false });

o.v = 2; // 报错

严格模式下,对一个使用getter方法读取的属性进行赋值,会报错。

"use strict";

var o = {

get v() { return 1; }

};

o.v = 2; // 报错

严格模式下,对禁止扩展的对象添加新属性,会报错。

"use strict";

var o = {};

Object.preventExtensions(o);

o.v = 1; // 报错

严格模式下,删除一个不可删除的属性,会报错。

"use strict";

delete Object.prototype; // 报错

4.6 重名错误

严格模式新增了一些语法错误。

(1)对象不能有重名的属性

正常模式下,如果对象有多个重名属性,最后赋值的那个属性会覆盖前面的值。严格模式下,这属于语法错误。

"use strict";

var o = {
p: 1,
p: 2
}; // 语法错误

(2)函数不能有重名的参数

正常模式下,如果函数有多个重名的参数,可以用arguments[i]读取。严格模式下,这属于语法错误。

"use strict";

function f(a, a, b) { // 语法错误

return ;

}

4.7 禁止八进制表示法

正常模式下,整数的第一位如果是0,表示这是八进制数,比如0100等于十进制的64。严格模式禁止这种表示法,整数第一位为0,将报错。

"use strict";

var n = 0100; // 语法错误

4.8 arguments对象的限制

arguments是函数的参数对象,严格模式对它的使用做了限制。

(1)不允许对arguments赋值

"use strict";

arguments++; // 语法错误

var obj = { set p(arguments) { } }; // 语法错误

try { } catch (arguments) { } // 语法错误

function arguments() { } // 语法错误

var f = new Function("arguments", "&#39;use strict&#39;; return 17;"); // 语法错误

(2)arguments不再追踪参数的变化

  function f(a) {

a = 2;

return [a, arguments[0]];

}

f(1); // 正常模式为[2,2]

function f(a) {

"use strict";

a = 2;

return [a, arguments[0]];

}

f(1); // 严格模式为[2,1]

(3)禁止使用arguments.callee

这意味着,你无法在匿名函数内部调用自身了。

"use strict";

var f = function() { return arguments.callee; };

f(); // 报错

4.9 函数必须声明在顶层

将来Javascript的新版本会引入”块级作用域”。为了与新版本接轨,严格模式只允许在全局作用域或函数作用域的顶层声明函数。也就是说,不允许在非函数的代码块内声明函数。

"use strict";

if (true) {

function f() { } // 语法错误

}

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

function f2() { } // 语法错误

}

4.10 保留字

为了向将来Javascript的新版本过渡,严格模式新增了一些保留字:implements, interface, let, package, private, protected, public, static, yield。

使用这些词作为变量名将会报错。

function package(protected) { // 语法错误

"use strict";

var implements; // 语法错误

}

此外,ECMAscript第五版本身还规定了另一些保留字(class, enum, export, extends, import, super),以及各大浏览器自行增加的const保留字,也是不能作为变量名的。

相关推荐:编程视频课程

The above is the detailed content of Detailed explanation of Javascript strict mode. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:webhek. If there is any infringement, please contact admin@php.cn delete
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools