search
HomeWeb Front-endJS TutorialA brief analysis of what you need to know about strict mode in js

The content this article brings to you is about the content that needs to be mastered in a brief analysis of strict mode in js. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

strict mode

First of all, let’s understand what strict mode is?
Strict mode is a more restrictive variant of JavaScript, not a subset: it is semantically significantly different from normal code, browsers that do not support strict mode and browsers that support strict mode The behavior is also different, so do not use strict mode without testing strict mode features. Strict mode can coexist with non-strict mode, so scripts can gradually and selectively join strict mode

  • The purpose of strict mode

First of all, strict mode will directly turn JavaScript traps into obvious errors. Secondly, strict mode corrects some errors that are difficult for engines to optimize: the same code has some Sometimes strict mode will be faster than non-strict mode. Thirdly, strict mode disables some syntax that may be defined in future versions

  • Enable strict mode globally

If you want to enable strict mode in JavaScript, you need to define a string that will not be assigned to any variable before all code:

'use strict';//或者"use strict"

If the previous JavaScript is in non-strict mode, It is recommended not to blindly enable strict mode for this code, as this may cause problems. It is recommended to enable strict mode one by one.
You can also enable strict mode for a specified function:

//函数外部依旧是非严格模式
function fun(){
    'user strict';//开启严格模式
}

In Anonymous Using strict mode in a function is equivalent to an alternative implementation of turning on strict mode globally

(function(){
    'use strict';//开启严格模式
})();
  • Accidental creation of variables is prohibited

In strict mode , accidental creation of global variables is not allowed
The following example code is the accidental creation of global variables in non-strict mode

//未声明的变量
result='这是一个没用var声明的全局变量';

The following example code is the accidental creation of global variables in strict mode

'use strict';//开启严格模式
//严格模式下,意外创建全局变量,抛出ReferenceError
message='this is message';//ReferenceError: result is not defined
  • Silent failure is converted into an exception

Silent failure means neither reporting an error nor having any effect, such as changing the value of a constant. In strict mode, silent failure will be converted into throwing an exception. Note: This is divided into browsers, some browsers will, and some will not
The following code is a silent failure in non-strict mode

const PI=3.14;
PI=1.14;//静默失败
console.log(PI);//3.14

The following code is a silent failure in strict mode

'use strict';//开启严格模式

const PI=3.14;
PI=1.14;//抛出TypeError错误
  • Disable delete keyword

In strict mode, the delete operator cannot be used on variables
The following example code uses the delete operator in non-strict mode , the result will fail silently

var color='red';
delete color;

The following example code uses the delete operator in strict mode, and the result will throw an exception

'use strict';//开启严格模式

var color='red';
delete color;//SyntaxError: Delete of an unqualified identifier in strict mode.
  • Restrictions on variable names

In strict mode, JavaScript also has restrictions on variable names. In particular, you cannot use implements, interface, let, package, private, protected, public, stalic, and yield as variable names. They are all Reserved words, they may be used in the next version of ECMAScript. In strict mode, using these identifiers as variable names will cause syntax errors

  • Non-removable attributes

In strict mode, the delete operator cannot be used to delete non-deletable attributes
The following example code uses the delete operator to delete non-deletable attributes in non-strict mode, and the result is a silent failure

delete Object.prototype;

The following example code uses the delete operator to delete non-deletable attributes in strict mode. The result will be an exception.

'use strict';//开启严格模式
delete Object.prototype;//TypeError: Cannot delete property 'prototype' of function Object() { [native code] }
  • The attribute name must be unique

In strict mode, all attribute names of an object must be unique within the object.
The following example code shows that duplicate-named attributes are allowed in non-strict mode. The last duplicate-named attribute determines its attribute value.

var o={p:1,p:2};

The following example code is a syntax error for attributes with duplicate names in strict mode

'use strict';//开启严格模式
var o={p:1,p:2};//不报错但是语法错误
  • Assignment of read-only attributes

In strict mode, a read-only attribute cannot be reassigned
The following example code is a non-strict mode reassignment of a read-only attribute, and the result will be a silent failure

var obj={};
Object.defineProperty(obj,'name',{
    value:'张三',
    writable:false
});//将属性设置为只读
obj.name='李四';

The following example code is in strict mode The read-only property is reassigned below, and an exception will be thrown.

'use strict';//开启严格模式
var obj={};
Object.defineProperty(obj,'name',{
    value:'张三',
    writable:false
});//将属性设置为只读
obj.name='李四';//TypeError: Cannot assign to read only property 'name' of object '#<object>'</object>
  • Non-extensible object

In strict mode, it cannot be non-extensible Adding new properties to an extended object
The following code is to add new properties to non-extensible objects in non-strict mode, and the result will be a silent failure

var obj={};
Object.preventExtensinons(obj);//将对象设置为不可扩展
obj.name='张三';

The following code is to add new properties to non-extensible objects in strict mode. The result will throw an exception

'use strict';//开启严格模式

var obj={};
Object.preventExtensions(obj);//将对象变得不可扩展
obj.name='张三';//TypeError: Cannot add property name, object is not extensible
  • Parameter names must be unique

In strict mode, the parameters of the named function must be unique
The example code is that the last parameter with the same name in non-strict mode will cover up the previous parameters with the same name. The previous parameters can still be accessed through arguments[i]

function sum(a,a,c){}

The following example code is the parameter with the same name in the strict mode. Think it is a syntax error

function sum(a,a,c){//语法错误
    'use strict';
    return a+a+c;//代码运行到这里会出错:SyntaxError: Duplicate parameter name not allowed in this context
}
  • Difference in arguments

在严格模式下,arguments对象的行为也有所不同
1.非严格模式下,修改命名参数的值也会反应到arguments对象中
2.严格模式下,命名参数与arguments对象是完全独立的

function fun(value){
    value='haha';
    console.log(value);//haha
    console.log(arguments[0]);//非严格模式下 hah
                              //严格模式下 hello
}

showValue('hello');
``

 - arguments.callee()
在严格模式下,不能使用arguments对象的callee()方法
下例代码是非严格模式下使用arguments对象的callee()方法,表示调用函数本身
var f=function(){
return arguments.callee;
};
f();
下例代码是严格模式下使用arguments对象的callee()方法,结果会抛出异常
'use strict';//开启严格模式
var f=function(){
return arguments.callee;
}
f();
/TypeError: 'caller', 'callee', and 'arguments' properties 
may not be accessed on strict mode functions or the arguments objects 
for calls to them/
 - 函数声明的限制
在严格模式下,只能在全局域和函数域中声明函数
下例代码非严格模式下在任何位置声明函数都是合法的
if(true){
function f(){}
}
下例是严格模式下在除全局域和函数域中声明函数是语法错误
'use strict';//开启严格模式
if(true){
function f(){}//语法错误,但是不报错
}
 - 增加eval作用域
在严格模式下,使用eval()函数创建的变量只能在eval()函数内部使用
下例代码是非严格模式下eval()函数创建的变量在其他位置可以使用
eval(&#39;var n=40&#39;);
console.log(n);//40
下例代码是严格模式下eval()函数创建的变量只能在eval()函数内部使用
&#39;use strict&#39;;//开启严格模式
eval(&#39;var n=40&#39;);
console.log(n);//ReferenceError: n is not defined
 - 禁止读写
在严格模式下,禁止使用eval()和arguments作为标识符,也不允许读写它们的值
1.使用var声明
2.赋予另一个值
3.尝试修改包含的值
4.用作函数名
5.用作命名的函数的参数
6.在try...catch语句中用作例外名
在严格模式下,以下所有尝试将导致语法错误:
&#39;use strict&#39;;//开启严格模式
eval=17;
arguments++;
++eval;
var obj={set p(arguments){}};
var eval;
try{}catch(arguments){}
function x(eval){}
function argunments(){}
var y=function eval(){}
var f=new Function(&#39;arguments&#39;,&#39;"use strict";return 20;&#39;);
 - 抑制this
在非严格模式下使用函数apply()或call()方法时,null或undefined值会被转换为全局对象
在严格模式下,函数的this值始终是指定的值(无论什么值)。
var color='red';
function sayColor(){
console.log(this.color);//非严格模式下 red
                    /*严格模式下:TypeError: Cannot 
                     read property 'color' of null*/
                     }

相关推荐:

JS设计模式之构造器模式详解

怎么使用JS严格模式

The above is the detailed content of A brief analysis of what you need to know about strict mode in js. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
Javascript Data Types : Is there any difference between Browser and NodeJs?Javascript Data Types : Is there any difference between Browser and NodeJs?May 14, 2025 am 12:15 AM

JavaScript core data types are consistent in browsers and Node.js, but are handled differently from the extra types. 1) The global object is window in the browser and global in Node.js. 2) Node.js' unique Buffer object, used to process binary data. 3) There are also differences in performance and time processing, and the code needs to be adjusted according to the environment.

JavaScript Comments: A Guide to Using // and /* */JavaScript Comments: A Guide to Using // and /* */May 13, 2025 pm 03:49 PM

JavaScriptusestwotypesofcomments:single-line(//)andmulti-line(//).1)Use//forquicknotesorsingle-lineexplanations.2)Use//forlongerexplanationsorcommentingoutblocksofcode.Commentsshouldexplainthe'why',notthe'what',andbeplacedabovetherelevantcodeforclari

Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

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.

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 Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools