ES6新增特性 (一
1. let关键字
1.1 无法重复声明变量
let a = 1;
let a = 2; // Uncaught SyntaxError: Identifier 'a' has already been declared
1.2 引进块级作用域
{
let a = 1;
}
console.log(a) // Uncaught ReferenceError: a is not defined
1.3 不存在变量提升
console.log(a); // Uncaught ReferenceError: Cannot access 'a' before initialization
let a = 1;
2. const关键字
2.1 变量名一般使用全大写
const SCHOOL = 'YC';
2.2 需赋初值
const SCHOOL; // Uncaught SyntaxError: Missing initializer in const declaration
2.3 当值是基本数据类型时,不可更改
const SCHLLO = 'YC';
SCHLLO = 'ZY'; // Uncaught TypeError: Assignment to constant variable
2.4 具有块级作用域
{
const SCHLLO = 'YC';
}
console.log(SCHLLO); // Uncaught ReferenceError: SCHLLO is not defined
2.5 当值是对象时,可对其操作
const ARR = [1, 2, 3];
ARR.push(4);
console.log(ARR); // [1, 2, 3, 4]
const OBJ = { name: 'G' }
OBJ.name = 'L'
console.log(OBJ) // {name: "L"}
3. 解构赋值
3.1 对数组进行解构
const TEAM = ['游星', '鬼柳'];
let [y, g] = TEAM;
console.log(y); // 游星
console.log(g); // 鬼柳
3.2 对对象进行解构
let obj = {
name: '鬼柳',
age: 17,
test: function() {
console.log('test method')
}
}
let {name, age, test} = obj
console.log(name, age) // 鬼柳 17
test() // test method
3.3 对对象进行解构赋值
let obj = {
name: '鬼柳';
}
// 在此处进行解构并赋值到newName变量中
let {name: newName} = obj;
console.log(newName); // 鬼柳
4. 模板字符串
var team = ['乌鸦', '杰克'];
// 1.可直接出现换行
// 2. 可访问变量
console.log(`<ul>
<li>${team[0]}</li>
<li>${team[1]}</li>
</ul>`)
5. 对象简化
var name = '鬼柳';
var age = 17;
var obj = {
// 当属性名和需要引用的变量名相同时,可只写一次
name,
age,
// 优化方法定义
test() {
console.log('test method')
}
}
6. 箭头函数
6.1 this指向
箭头函数中的this指向声明作用域下this
window.name = '鬼柳'
function getName() {
console.log(this.name)
}
let getName2 = () => {
console.log(this.name)
}
var obj = {
name: '游星',
getName: () => {
console.log(this.name)
}
}
getName.call(obj) // 游星
getName2.call(obj) // 鬼柳
6.2 无法作为构造函数
let Obj = (name, age) => {
this.name = name;
this.age = age;
}
let gl = new Obj('鬼柳', 17) // Uncaught TypeError: Obj is not a constructor
6.3 无法使用arguments
let fu = () => {
console.log(arguments) // Uncaught ReferenceError: arguments is not defined
}
fu()