阅读目录
undefined
- undefined
- null
- 严格模式
- 基本差异
- 解构差异
对声明但未赋值的变量返回类型为 undefined
表示值未定义。
let hd;
console.log(typeof hd);
对未声明的变量使用会报错,但判断类型将显示
undefined
。
console.log(typeof wgchen);
console.log(wgchen);
我们发现未赋值与未定义的变量值都为
undefined
,建议声明变量设置初始值,这样就可以区分出变量状态了。
函数参数或无返回值是为 undefined
function hd(web) {
console.log(web); //undefined
return web;
}
console.log(hd()); //undefined
null
null
用于定义一个空对象,即如果变量要用来保存引用类型,可以在初始化时将其设置为null
var hd = null;
console.log(typeof hd);
严格模式可以让我们及早发现错误,使代码更安全规范,推荐在代码中一直保持严格模式运行。
主流框架都采用严格模式,严格模式也是未来JS标准,所以建议代码使用严格模式开发
基本差异变量必须使用关键词声明,未声明的变量不允许赋值
"use strict";
url = 'https://wgchen.blog.csdn.net'; //url is not defined
强制声明防止污染全局
"use strict";
function run() {
web = "wgchen";
}
run();
console.log(web); //wgchen
关键词不允许做变量使用
"use strict";
var public = 'wgchen';
变量参数不允许重复定义
"use strict";
//不允许参数重名
function hd(name, name) {}
单独为函数设置严格模式
function strict(){
"use strict";
return "严格模式";
}
function notStrict() {
return "正常模式";
}
为了在多文件合并时,防止全局设置严格模式对其他没使用严格模式文件的影响,将脚本放在一个执行函数中。
(function () {
"use strict";
url = 'wgchen';
})();
解构差异
非严格模式可以不使用声明指令,严格模式下必须使用声明。 所以建议使用 let 等声明。
// "use strict";
({name,url} = {name:'wgchen',url:'https://wgchen.blog.csdn.net'});
console.log(name, url);
"use strict";
({name,url} = {name:'wgchen',url:'https://wgchen.blog.csdn.net'});
console.log(name, url);
"use strict";
let persion = {name:'wgchen',url:'https://wgchen.blog.csdn.net'};
console.log(persion);