ES6新特性总结

ES全称ECMAScript,ECMAScript是ECMA制定的标准化脚本语言

ES6新特性(2015)

ES6的特性较多,在 ES5 发布近 6 年(2009.11 - 2015.6)之后才将其标准化。ES6常用特性的有11个,如下所示:

  • 类: class  让JavaScript的面向对象编程变得更加简单和易于理解
  • 模块化:模块的功能主要由 export 和 import 组成,export 对外暴露(导出),import 引用(导入),同时为模块创造了命名空间
  • 箭头函数:=> 是关键词function的缩写,左边为参数,右边为具体操作和返回值,this指向是包裹他的函数
  • Let与 Const:let与const都是块级作用域,var变量申明提前;let定义变量;const定义常量,并且得及时赋值
  • 模板字符串:使得字符串拼接更加简洁直观
  • 解构赋值:可以从数组或对象中快速取值赋给定义的变量,按顺序一 一对应
  • 三点运算符:通过它可以将数组作为参数直接传入函数,在函数定义时可以通过…rest获取定义参数外的所有参数
  • 对象属性简写:不使用ES6时,对象中必须包含属性和对应的值,而ES6可以只写变量
  • Promise:异步编程,可解决回调地狱
  • 函数参数默认值:ES6支持在定义函数的时候为其设置默认值,不仅更简洁且能够回避一些问题
  • iterable类型:为统一集合类型,Array、Map和Set都是iterable类型,可以通过for...of循环来遍历
实例代码
1、类                                                                                                                                                                                                                 
 
  class Animal {
    // 构造函数,实例化的时候将会被调用,如果不指定,那么会有一个不带参数的默认构造函数.
    constructor(name,color) {
      this.name = name;
      this.color = color;
    }
    // toString 是原型对象上的属性
    toString() {
      console.log('name:' + this.name + ',color:' + this.color);

    }
  }

 var animal = new Animal('dog','white');//实例化Animal
 animal.toString();

 console.log(animal.hasOwnProperty('name')); //true
 console.log(animal.hasOwnProperty('toString')); // false
 console.log(animal.__proto__.hasOwnProperty('toString')); // true

 class Cat extends Animal {
  constructor(action) {
    // 子类必须要在constructor中指定super 函数,否则在新建实例的时候会报错.
    // 如果没有置顶consructor,默认带super函数的constructor将会被添加、
    super('cat','white');
    this.action = action;
  }
  toString() {
    console.log(super.toString());
  }
 }

 var cat = new Cat('catch')
 cat.toString();

 // 实例cat 是 Cat 和 Animal 的实例,和Es5完全一致。
 console.log(cat instanceof Cat); // true
 console.log(cat instanceof Animal); // true

2、模块化                                                                                                                                                                                                             

// ES6将一个文件视为一个模块,上面的模块通过 export 向外输出了一个变量。一个模块也可以同时往外面输出多个变量。
 var name = 'Rainbow';
 var age = '24';
 export {name, age};


// 导出函数
export function myModule(someArg) {
  return someArg;
}  

// 导入
import {myModule} from 'myModule';// main.js
import {name,age} from 'test';// test.js

3、箭头函数                                                                                                                                                                                                          

// ES6中新增箭头操作符用于简化函数的写法,操作符左边为参数,右边为具体操作和返回值
var sum = (num1, num2) => { return num1 + num2; }
//等同于
var sum = function(num1, num2) {
    return num1 + num2;
};

// 箭头函数还修复了this的指向,使其永远指向词法作用域
var obj = {
    birth: 1990,
    getAge: function () {
        var b = this.birth; // 1990
        var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
        return fn();
    }
};
obj.getAge(); // 25

4、let 与 const                                                                                                                                                                                                      

{
  var a = 10;
}

console.log(a); // 输出10

{
  let a = 10;
}

console.log(a); //-1 or Error“ReferenceError: a is not defined”

const PI = 3.1415;
PI // 3.1415
PI = 3; //TypeError: Assignment to constant variable.

5、模板字符串                                                                                                                                                                                                      

//  不使用模板字符串
var name = 'Your name is ' + first + ' ' + last + '.'

//  使用模板字符串
var name = `Your name is ${first} ${last}.`
//  通过${}就可以完成字符串的拼接,只需要将变量放在大括号之中

6、解构赋值                                                                                                                                                                                                         

var foo = ["one", "two", "three", "four"];

var [one, two, three] = foo;
console.log(one); // "one"
console.log(three); // "three"

//如果你要忽略某些值,
var [first, , , last] = foo;
console.log(first); // "one"
console.log(last); // "four"


var a, b; //先声明变量
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2

var a, b;
[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7


var a = 1;
var b = 3;
[a, b] = [b, a];
console.log(a); // 3
console.log(b); // 1

const student = {
  name:'Ming',
  age:'18',
  city:'Shanghai'  
};
const {name,age,city} = student;
console.log(name); // "Ming"
console.log(age); // "18"

7、三点运算符                                                                                                                                                                                                         

function sum(x, y, z) {
  return x + y + z;
}
const numbers = [1, 2, 3];
//不使用延展操作符
console.log(sum.apply(null, numbers));
//使用延展操作符
console.log(sum(...numbers));// 6

const stuendts = ['Jine','Tom']; 
const persons = ['Tony',... stuendts,'Aaron','Anna'];
conslog.log(persions)// ["Tony", "Jine", "Tom", "Aaron", "Anna"]

var obj1 = { foo: 'bar', x: 42 };
var obj2 = { foo: 'baz', y: 13 };
var clonedObj = { ...obj1 };
// 克隆后的对象: { foo: "bar", x: 42 }

var mergedObj = { ...obj1, ...obj2 };
// 合并后的对象: { foo: "baz", x: 42, y: 13 }

const params = {
    name: 'Jine',
    age: 21
}
<CustomComponent {...params} />

8、对象属性简写                                                                                                                                                                                                      

const name='Ming',age='18',city='Shanghai';
   
const student = {
    name:name,
    age:age,
    city:city
}; //  不用ES6

const student = {
    name,
    age,
    city
};  //  用了ES6

9、Promise                                                                                                                                                                                                              

setTimeout(function()
{
    console.log('Hello'); // 1秒后输出"Hello"
    setTimeout(function()
    {
        console.log('Hi'); // 2秒后输出"Hi"
    }, 1000);
}, 1000);

var waitSecond = new Promise(function(resolve, reject) { setTimeout(resolve, 1000); }); waitSecond .then(function() { console.log("Hello"); // 1秒后输出"Hello" return waitSecond; }) .then(function() { console.log("Hi"); // 2秒后输出"Hi" });

10、函数参数默认值                                                                                                                                                                                            

function foo(height, color)
{
    var height = height || 50;
    var color = color || 'red';
    //...不使用默认值  (参数的布尔值为false会出问题)
}


function foo(height = 50, color = 'red')
{
    // ...使用了默认值
}

11、iterable类型                                                                                                                                                                                                  

var a = ['A', 'B', 'C'];
var s = new Set(['A', 'B', 'C']);
var m = new Map([[1, 'x'], [2, 'y'], [3, 'z']]);
for (var x of a) { // 遍历Array
    alert(x);
}
for (var x of s) { // 遍历Set
    alert(x);
}
for (var x of m) { // 遍历Map
    alert(x[0] + '=' + x[1]);

//  Map相关操作如下,Set同理
var m = new Map(); // 空Map
m.set('Adam', 67); // 添加新的key-value
m.set('Bob', 59);
m.has('Adam'); // 是否存在key 'Adam': true
m.get('Adam'); // 67
m.delete('Adam'); // 删除key 'Adam'
m.get('Adam'); // undefined

猜你喜欢

转载自www.cnblogs.com/zhou-xm/p/10776036.html