严格模式
定义严格模式的两种方式
1、“use strict”
"use strict"
2. type=“module”
在script标签内定义type="module"就可以
<script type="module">
</script>
使用
1、严格模式下未使用 var定义的变量都会报错
a = 100;
console.log(a)
a = 100;
console.log(a)
例子
console.log(a);
a=3;
function a(){
}
console.log(a);
var a = 5;
2、函数的参数不能同名
function fn(a, a) {
console.log(a, a);
}
fn(3, 5);
案例
var a = 3;
{
a = 4;
function a() {
console.log("a")
}
a = 5;
function a() {
console.log("b")
}
a = 6;
console.log(a, "___1") 6
}
console.log(a, "___2") 5
var a = 5;
if (a < 6) {
function a() {
}
}
console.log(a);
function fn(a) {
if (a === undefined) {
a = "你好";
} else {
var a = 3;
}
console.log(a);
}
fn(2);
3、不能使用with语句
var div = document.createElement("div");
div.style.width = "50px";
div.style.height = "50px";
div.style.backgroundColor = "red";
with (div.style) {
width = "50px";
height = "50px";
backgroundColor = "red";
}
var obj ={ a:{ b:{ c:1,d:2 } } }
with(obj.a.b){c=3;d=5;}
console.log(obj)
var obj = {
a: {
b: {
c: 1,
d: 2
}
}
}
with (obj.a.b) {
c = 3;
d = 5;
e = 10;
}
console.log(obj)
console.log(e)
不能修改只读属性
var str = "aaaaa";
str.length = 10;
不能删除不可删除属性
var str = "aaaaa";
delete str.length;
var arr = [1, 2, 3];
delete arr.length;
console.log(arr.length)
不能使用前缀0八进制
var x = 046;
在严格模式下不能使用arguments.callee,arguments.callee.caller
在严格模式下不能使用arguments.callee,arguments.callee.caller
function fn() {
console.log(arguments.callee)
console.log(arguments.callee.caller);
}
function fn1() {
fn(1, 2, 3);
}
fn1();
document.addEventListener("click", function () {
console.log("aa")
document.removeEventListener("click", arguments.callee);
})
禁止this指向全局对象
console.log(this)
function fn(){
console.log(this);
}
fn()
var obj = {
a: function (f) {
f();
},
b: function () {
console.log(this);
}
}
obj.a(obj.b);
setTimeout(obj.b, 1000);
setTimeout(obj.b(), 1000);
举例:我让张三帮我带饭 这是我直接给张三说的 这是直接执行的 指向的是obj
我让小李给张三说 让张三给我带饭 这就是回调函数 这是我让小李去执行的
知识点 反射 eval
var obj = { a: 1,b: 2}
console.log(eval("obj"))
console.log(eval("10+30"))
虽然很好用 但是不要在严格模式用eval