严格模式
所有js程序都运行在严格模式下
在当前代码段的顶部添加 use strict
禁止给未声明的变量赋值
<script>
"use strict";
function send(){
var gf;
gf="今晚308,考试学习补考";
console.log(`差生收到${gf}`);
}
send();
</script>
静默失败升级为错误
程序执行不成功也不报错就是静默失败
在严格模式下静默失败会报错
想要把员工编号修改为2,却没有修改成功,也没有报错
eg:<body>
<script>
var eric={
eid:1001,
ename:"li"
}
//公司规定,员工编号,禁止修改,写时忘了自已设置了。
Object.defineProperty(eric,"eid",{
writable:false
})
//修改属性值
eric.eid=2;
console.log(eric.eid);
</script>
</body>
严格模式下,会给出错误原因
<body>
<script>
"use strict";
var eric={
eid:1001,
ename:"li"
}
//公司规定,员工编号,禁止修改,写时忘了自已设置了。
Object.defineProperty(eric,"eid",{
writable:false
})
//修改属性值
eric.eid=2;
console.log(eric.eid);
</script>
</body>
严格模式下,普通函数调用时,this不再指向window,而是指向undefined,不会造成全局污染
普通模式下,this在没有.和new时指向全局,容易造成全局污染
<script>
function Student(sname,sage){
this.sname=sname;
this.sage=sage;
}
var lilei=new Student("li",19);
//this->new创建的对象lilei
//this.sname=sname->lilei.sname=sname
//this.sage=sage->llei.sage=sage
var hmm=Student("hmm",15);//没有new没有对象,所以hmm这个对象什么也得不到
//this->window
//this.sname=sname->window.sname=sname
//this.sage=sage->window.sage=sage
console.log(lilei,hmm);
//hmm的两个属性泄漏到了全局
console.log(sname,sage);
</script>
严格模式下
<script>
"use strict";
function Student(sname,sage){
this.sname=sname;
this.sage=sage;
}
var lilei=new Student("li",19);
var hmm=Student("hmm",15);
console.log(lilei,hmm);
console.log(sname,sage);
</script>
禁用arguments.callee
argument另一个用处是重载,不用形参接收实参,用arguments 判断实参个数
arguments.callee 在函数调用时,自动获得当前函数本身的关键字,只要是递归就可以它。
eg:
<body>
<script>
//斐波那契数列
//1 1 2 3 5 8 13 21 34 55
//f(1)=1 f(2)=1 f(n)=f(n-2)+f(n-1)
function fn(n){
if(n<3){
return 1
}else{
return fn(n-2)+fn(n-1)//以后看能不能把这里弄明白
}
}
console.log(fn(10));
function student(n)
{
if(n<3){
return 1
}else{
return student(n-2)+student(n-1)
}
}
var s=student(10);//注意这里的10不是指10这个数字,而是斐波那契数列第10位数的值,也就是说return student(n-2)+student(n-1),这里的n-1,n-2指的是第8位数和第九位数,把他们相加就行。
console.log(s);
</script>
</body>
arguments.callee 可以防止函数名写死,函数出错
函数名变化,无影响
<body>
<script>
//斐波那契数列
//1 1 2 3 5 8 13 21 34 55
//f(1)=1 f(2)=1 f(n)=f(n-2)+f(n-1)
function f(n){
if(n<3){
return 1
}else{
// return fn(n-2)+fn(n-1)
return arguments.callee (n-1)+arguments.callee (n-2)
}
}
console.log(f(10));
</script>
</body>
递归的重复计算量太大,效率低,所以在严格模式下使用会报错。
所以如果真的需要使用时,计算量不要很大,或者很影响效率的情况下,用循环代替。
<body>
<script>
"use strict";
//斐波那契数列
//1 1 2 3 5 8 13 21 34 55
//f(1)=1 f(2)=1 f(n)=f(n-2)+f(n-1)
function f(n){
if(n<3){
return 1
}else{
// return fn(n-2)+fn(n-1)
return arguments.callee (n-1)+arguments.callee (n-2)
}
}
console.log(f(10));
</script>
</body>