1. 新增数据类型(Symbol
)
- 介绍
- Symbol类型的值通过Symbol函数生成,相同Symbol函数返回的值是唯一的。
- Symbol函数可以接收字符串作为参数,但是即使相同参数返回的也是唯一值,即
Symbol('miaov') != Symbol('miaov')
- 实例
打印结果:外部:undefined 、内部:男
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Symbol实例</title> </head> <body> <script> /* *Symbol一般用于属性保护,即属性私有化 *属性私有化:即方法内部可以访问,但方法外部不可以访问 */ var Person = (function(){ var _gender = Symbol('gender'); function P(name,gender){ this.name = name; this[_gender] = gender; } P.prototype.say= function() { console.log('内部'+this[_gender]) } return P; })(); var p1 = new Person('风雅', '男'); console.log('外部'+p1[Symbol('_gender')]); console.log(p1.say()); </script> </body> </html>
2.新增变量声明——const
2.1 const
常量声明,一经声明不能改变(如果声明的常量是一个复合类型,那么只要不修改这个常量的指向地址,则不会报错,添加删除属性都是ok的)
- 不支持变量声明预解析(先声明后使用)
- 支持块作用域
- 不允许重复声明(暂存死区)
const b = 2;//正确
// const b;//错误,必须初始化
console.log('函数外const定义b:' + b);//有输出值
// b = 5;
// console.log('函数外修改const定义b:' + b);//无法输出
### 2.2 Let
- 不支持变量声明预解析(先声明后使用)
-
支持块作用域
-
不允许重复声明(暂存死区)
点击按钮一:打印0
点击按钮二:打印1
点击按钮三:打印2
即对应的索引值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
button.active {
background: pink;
}
p {
display: none;
}
p.active {
display: block;
}
</style>
</head>
<body>
<button class="active">按钮一</button>
<button>按钮二</button>
<button>按钮三</button>
<p class="active">内容一</p>
<p>内容二</p>
<p>内容三</p>
</body>
<script>
btns = document.querySelectorAll('button');
ps = document.querySelectorAll('p');
for (let i=0; i<btns.length; i++){
btns[i].onclick=function(){
console.log(i);
}
}
</script>
</html>
2.3 var
- 支持变量声明预解析
-
不支持块作用域
-
允许重复声明
点击按钮一:打印3
点击按钮二:打印3
点击按钮三:打印3
即打印循环结束时i的值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
button.active {
background: pink;
}
p {
display: none;
}
p.active {
display: block;
}
</style>
</head>
<body>
<button class="active">按钮一</button>
<button>按钮二</button>
<button>按钮三</button>
<p class="active">内容一</p>
<p>内容二</p>
<p>内容三</p>
</body>
<script>
btns = document.querySelectorAll('button');
ps = document.querySelectorAll('p');
for (var i=0; i<btns.length; i++){
btns[i].onclick=function(){
console.log(i);
}
}
</script>
</html>