一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第20天,点击查看活动详情。
我们都知道js有严格模式与非严格模式的区别,大部分我们写练习的时候使用的都是非严格模式。严格模式的使用频次是相对较少的。那么今天就简单的记录一下严格模式的特点。(js严格模式的特点有很多,本次只记录一部分,有机会后续会继续在这篇文章中增加)
使用
JavaScript 严格模式(strict mode)即在严格的条件下运行,使用 "use strict" 指令
- 全局开启
"use strict"
function test(){
...
}
...
- 针对某个函数开启
function test(){
"use strict"
...
}
...
特点
1. 全局变量必须先声明
如果声明一个全局变量,在非严格模式下,我们直接写
<script>
n = 10;
console.log(n)
</script>
这样虽然不太好,但是它并不会报错,并且控制台会打印出10的结果
但是如果将代码写成
<script>
"use strict"
n = 10;
console.log(n)
</script>
那么控制台会直接报错“Uncaught ReferenceError: n is not defined”
想要正确打印结果,全局变量必须要用var、const或者let先声明
2. 禁止使用with
- 先简单介绍一下with的用法
-
语法
with (expression) { statement } -
举例
const obj = {a:1, b:2}
console.log(obj.a)//1
with(obj){
console.log(a)//1
}
如果在严格模式下使用,浏览器和编辑器都会报错,上图为敬
3. 创建eval作用域
- 非严格模式
var testEval = 10;
eval(`var testEval = 20;console.log('in:',testEval)`) //in: 20
console.log("out:",testEval) //out: 20
- 严格模式
"use strict"
var testEval = 10;
eval(`var testEval = 20;console.log('in:',testEval)`) //in: 20
console.log("out:",testEval) //out: 10
上方的代码示例就是告诉我们在严格模式下为eval创建了属于它自己的作用域,eval里外互不干扰。 tips:eval不推荐使用
4. 禁止this指向window
- 非严格模式
function testThis(){
console.log('this:',this)
}
testThis()
上方代码打印结果大家都知道,是this:window对象
- 严格模式
function testThis(){
console.log('this:',this)
}
testThis()
上方代码打印结果为this: undefined
tips: 这里的this,依然可以使用apply等进行改变
5. 函数参数不能重名
- 非严格模式
function testRepeatName(x, x, y){
console.log(arguments)
console.log(x)
console.log(y)
}
testRepeatName(10, 20, 30)
打印结果如下
重名的函数参数,以后传入的为主,可以正常打印
- 严格模式
"use strict"
function testRepeatName(x, x, y){
console.log(arguments)
console.log(x)
console.log(y)
}
testRepeatName(10, 20, 30)
浏览器控制台会直接报错
总结
js在严格模式下,主要需要注意上述的5个特点。尤其是注意this的指向问题,它是最容易被疏忽的地方。其实js在创建之初就是一门非常简单的语言,它在变得越来越完善,是不是像人一样在不断的完善自我呢?我们在成长的过程中也是需要在别人的帮助下不断进步完善的。