ES6的新特性

119 阅读1分钟

变量声明 let const 块级作用域 使用前必须声明 声明时必须赋值

  • let表声明变量
  • const 表声明常量 不能修改 声明时变量名用大写

模板字符串

  • 基本的字符串格式化 将表达嵌入字符串中 进行拼接 用${} 来界定
  • (``)

箭头函数 当你的函数只有一个参数时 可以省略掉括号 当只有一个表达式时可以省略 { return}

(()=>{
 return   
})

函数的参数默认值

// ES6之前,当未传入参数时,text = 'default'function printText(text) {
    text = text || 'default';
    console.log(text);
}

// ES6;
function printText(text = 'default') {
    console.log(text);
}
printText('hello'); // hello
printText();// default

Spread/Rest操作符 ...

  • 用于迭代器的时候 是一个Spread操作符
function foo(x,y,z) {
  console.log(x,y,z);
}
 
let arr = [1,2,3];
foo(...arr); // 1 2 3
  • 当被用于函数传参时 是一个Rest操作符 当被用于传参时 是一个Rest操作符
function foo(...args) {
 console.log(args);
}
foo( 1, 2, 3, 4, 5); // [1, 2, 3, 4, 5]

二进制和八进制的字面量 在数字前添加0o 和0b 转换成八进制

对象和数组解构


// 对象
const student = {
    name: 'Sam',
    age: 22,
    sex: '男'
}
// 数组
// const student = ['Sam', 22, '男'];

// ES5;
const name = student.name;
const age = student.age;
const sex = student.sex;
console.log(name + ' --- ' + age + ' --- ' + sex);

// ES6
const { name, age, sex } = student;
console.log(name + ' --- ' + age + ' --- ' + sex);

对象超类 允许在对象中使用super方法

var parent = {
  foo() {
    console.log("Hello from the Parent");
  }
}
 
var child = {
  foo() {
    super.foo();
    console.log("Hello from the Child");
  }
}

for in(用于遍历对象中的属性) 和 for of(遍历迭代器)

let letter = ['a', 'b', 'c'];
letter.size = 3;
for (let letter of letters) {
  console.log(letter);
}
// 结果: a, b, c

let stu = ['Sam', '22', '男'];
stu.size = 3;
for (let stu in stus) {
  console.log(stu);

ES6中的类 支持class语法 只是原型链的语法糖的表现形式