Home Web Front-end JS Tutorial Detailed explanation of JavaScript strict mode_javascript skills

Detailed explanation of JavaScript strict mode_javascript skills

May 16, 2016 pm 03:31 PM

As we know, JavaScript is a flexible language. Its flexibility also brings many pitfalls, and of course some are design flaws. For example

A variable is assigned a value without declaration. The default is a global variable, such as

(function () {
 a = 3;
})();
console.log(window.a); // 输出3
Copy after login

The object has multiple attributes with the same name, and the attribute assigned last will overwrite the previous value. Such as

var obj = {
 c: 3,
 c: 4
}
// obj 为 {c:4}
Copy after login

There are countless pitfalls like == and typeof. After all, the father of JavaScript only spent a week designing the language, haha.

What is strict mode in JavaScript

In the strict mode of JavaScript, there are some restrictions on how to write JavaScript. If these restrictions are violated in strict mode, the code will report an error.

1. Overview

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 main purposes of establishing "strict mode" are as follows:

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

- Eliminate some unsafe aspects of code operation and ensure the safety of code operation;

- Improve compiler efficiency and increase running speed;

- 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. Entry sign

The sign of entering "strict mode" is the following line:

"use strict";

Older versions of browsers will treat it as an ordinary string and ignore it.

3. How to call

"Strict mode" has two calling methods, 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.

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

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 "这是正常模式。";
}
Copy after login

3.3 Alternative ways 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 put the entire script file in an anonymous function that is executed immediately.

(function (){
  "use strict";
// some code here
})();
Copy after login

4. Grammar 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, it defaults to 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未声明
}
Copy after login

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

4.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 does not allow dynamic binding, only static binding. In other words, which object the properties and methods belong to must be 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;
}
Copy after login

(2)创设eval作用域

正常模式下,Javascript语言有两种变量作用域(scope):全局作用域和函数作用域。严格模式创设了第三种作用域:eval作用域。

正常模式下,eval语句的作用域,取决于它处于全局作用域,还是函数作用域。严格模式下,eval语句本身就是一个作用域,不再能够生成全局变量了,它所生成的变量只能用于eval内部。

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

4.3 增强的安全措施

(1)禁止this关键字指向全局对象

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

// 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。

因此,使用构造函数时,如果忘了加new,this不再指向全局对象,而是报错。

function f(){
  "use strict";
  this.a = 1;
};
f();
// 报错,this未定义
Copy after login

(2)禁止在函数内部遍历调用栈

function f1(){
  "use strict";
  f1.caller; 
// 报错
  f1.arguments; 
// 报错
}
f1();
Copy after login

4.4 禁止删除变量

严格模式下无法删除变量。只有configurable设置为true的对象属性,才能被删除。

"use strict";
var x;
delete x; 
// 语法错误
var o = Object.create(null, 'x', {
  value: 1,
  configurable: true
});
delete o.x; 
// 删除成功
Copy after login

4.5 显式报错

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

"use strict";
var o = {};
Object.defineProperty(o, "v", { value: 1, writable: false });
o.v = 2; 
// 报错
Copy after login

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

"use strict";
var o = {
get v() { return 1; }
};
o.v = 2; 
// 报错
Copy after login

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

"use strict";
var o = {};
Object.preventExtensions(o);
o.v = 1; 
// 报错
Copy after login

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

"use strict";
delete Object.prototype; 
// 报错
Copy after login

4.6 重名错误

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

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

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

"use strict";
var o = {
  p: 1,
  p: 2
}; 
// 语法错误
Copy after login

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

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

"use strict";
function f(a, a, b) { 
// 语法错误
  return ;
}
Copy after login

4.7 禁止八进制表示法

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

"use strict";
var n = 0100; 
// 语法错误
Copy after login

4.8 arguments对象的限制

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

(1)不允许对arguments赋值

"use strict";
arguments++; 
// 语法错误
var obj = { set p(arguments) { } }; 
// 语法错误
try { } catch (arguments) { } 
// 语法错误
function arguments() { } 
// 语法错误
var f = new Function("arguments", "'use strict'; return 17;"); 
// 语法错误
Copy after login

(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]
Copy after login

(3)禁止使用arguments.callee

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

"use strict";
var f = function() { return arguments.callee; };
f(); 
// 报错
Copy after login

4.9 函数必须声明在顶层

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

"use strict";
if (true) {
  function f() { } 
// 语法错误
}
for (var i = 0; i < 5; i++) {
  function f2() { } 
// 语法错误
}
Copy after login

4.10 保留字

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

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

function package(protected) { 
// 语法错误
  "use strict";
  var implements; 
// 语法错误
}
Copy after login

此外,ECMAscript第五版本身还规定了另一些保留字:class, enum, export, extends, import, super。它们也是不能使用的。

以上内容是小编给大家介绍的关于JavaScript严格模式详解的全部内容,希望大家喜欢。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 jQuery Fun and Games Plugins 10 jQuery Fun and Games Plugins Mar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

jQuery Parallax Tutorial - Animated Header Background jQuery Parallax Tutorial - Animated Header Background Mar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

How do I create and publish my own JavaScript libraries? How do I create and publish my own JavaScript libraries? Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

How do I optimize JavaScript code for performance in the browser? How do I optimize JavaScript code for performance in the browser? Mar 18, 2025 pm 03:14 PM

The article discusses strategies for optimizing JavaScript performance in browsers, focusing on reducing execution time and minimizing impact on page load speed.

Auto Refresh Div Content Using jQuery and AJAX Auto Refresh Div Content Using jQuery and AJAX Mar 08, 2025 am 12:58 AM

This article demonstrates how to automatically refresh a div's content every 5 seconds using jQuery and AJAX. The example fetches and displays the latest blog posts from an RSS feed, along with the last refresh timestamp. A loading image is optiona

Getting Started With Matter.js: Introduction Getting Started With Matter.js: Introduction Mar 08, 2025 am 12:53 AM

Matter.js is a 2D rigid body physics engine written in JavaScript. This library can help you easily simulate 2D physics in your browser. It provides many features, such as the ability to create rigid bodies and assign physical properties such as mass, area, or density. You can also simulate different types of collisions and forces, such as gravity friction. Matter.js supports all mainstream browsers. Additionally, it is suitable for mobile devices as it detects touches and is responsive. All of these features make it worth your time to learn how to use the engine, as this makes it easy to create a physics-based 2D game or simulation. In this tutorial, I will cover the basics of this library, including its installation and usage, and provide a

See all articles