Home > Web Front-end > JS Tutorial > A brief analysis of what you need to know about strict mode in js

A brief analysis of what you need to know about strict mode in js

不言
Release: 2018-08-29 16:20:35
Original
1322 people have browsed it

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"
Copy after login

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';//开启严格模式
}
Copy after login

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

(function(){
    'use strict';//开启严格模式
})();
Copy after login
  • 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声明的全局变量';
Copy after login

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
Copy after login
  • 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
Copy after login

The following code is a silent failure in strict mode

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

const PI=3.14;
PI=1.14;//抛出TypeError错误
Copy after login
  • 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;
Copy after login

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.
Copy after login
  • 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;
Copy after login

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] }
Copy after login
  • 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};
Copy after login

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

'use strict';//开启严格模式
var o={p:1,p:2};//不报错但是语法错误
Copy after login
  • 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='李四';
Copy after login

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>'
Copy after login
  • 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='张三';
Copy after login

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
Copy after login
  • 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){}
Copy after login

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

相关推荐:

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template