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>'
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!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

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

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.
