A 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('var n=40'); console.log(n);//40
下例代码是严格模式下eval()函数创建的变量只能在eval()函数内部使用
'use strict';//开启严格模式 eval('var n=40'); console.log(n);//ReferenceError: n is not defined
- 禁止读写 在严格模式下,禁止使用eval()和arguments作为标识符,也不允许读写它们的值 1.使用var声明 2.赋予另一个值 3.尝试修改包含的值 4.用作函数名 5.用作命名的函数的参数 6.在try...catch语句中用作例外名 在严格模式下,以下所有尝试将导致语法错误:
'use strict';//开启严格模式
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('arguments','"use strict";return 20;');- 抑制this 在非严格模式下使用函数apply()或call()方法时,null或undefined值会被转换为全局对象 在严格模式下,函数的this值始终是指定的值(无论什么值)。
var color='red';
function sayColor(){
console.log(this.color);//非严格模式下 red
/*严格模式下:TypeError: Cannot
read property 'color' of null*/
}
相关推荐:
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!
Python vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AMPython is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.
Python vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AMPython and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.
From C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AMThe shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.
JavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AMDifferent JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.
Beyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AMJavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.
Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AMI built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing
How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AMThis article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base
JavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AMJavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor







