es6 新特性


title: es6 新特性
preview: imgs/preview/es6_1.jpg
preview_text: es6 新特性 主要包含「類、模塊化、箭頭函數、函數參數默認值、模板字符串、解構賦值、延展操做符、對象屬性簡寫、Promise、let與const」
tags:
- javascript
---javascript

1. 類(class)

這三個特性涉及了ES5中最使人頭疼的的幾個部分:原型、構造函數,繼承...ES6提供了更接近傳統語言的寫法,引入了Class(類)這個概念。新的class寫法讓對象原型的寫法更加清晰、更像面向對象編程的語法,也更加通俗易懂。java

class Animal {
  constructor(name, color) {  // 構造函數
    this.name = name;
    this.color = color;
  }

  toString() { // toString方法
      console.log(`name: ${this.name}, color: ${this.color}`);
  }

  getName() {  // 取值
    return this.name;
  }
  setName(value) { // 存值
    this.name = value;
  }

  getColor() {  // 取值
    return this.color;
  }
  setColor(value) { // 存值
    this.color = value;
  }
}

let animal = new Animal("cat", "white");
animal.toString(); // name: cat, color: white

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

2. super 和 extends

使用新的super和extends關鍵字擴展類

class Cat extends Animal {
  constructor(action = "catch thing",name, color) {
    super("cat", "black"); // super用做函數, 必須在this使用前調用
    this.action = action; // Cat 類自己屬性
  }

  toString() {
    super.toString();// super用做對象
  }

  getAction() {
    return this.action;
  }

  setAction(value) {
      this.action = value;
  }
}

let cat = new Cat("eat fish");
cat.toString(); // name: cat, color: white
console.log(cat instanceOf Cat) // true
console.log(cat instanceOf Animal) // true

使用ES5編寫一樣功能的類

function Animal(name, color) {
  this.name = name || "cat";
  this.color = color || "orange";
}

Animal.prototype.toString = function() {
  console.log(`name: ${this.name}, color: ${this.color}`);
}

function Cat (action, name, color) {
  Animal.call(this, name, color);
  this.action = action || "catch thing";
}

Cat.prototype = Object.create(Animal.prototype);
Cat.prototype.constructor = Cat;

Cat.prototype.toString = function() {
  Tree.prototype.toString.call(this);
}

Cat.prototype.setAction = function(value) {
  this.action = value;
}

3. 模塊化(Module)

es5不支持原生的模塊化,在es6模塊做爲重要的組成部分被添加進來。模塊的共能主要由export和import組成。每個模塊都有本身的單獨的做用域,模塊之間的調用是經過export來規定模塊對外暴露的接口,經過import來引用其餘模塊提供的接口。同時模塊還創造了命名空間,防止函數的命名衝突。es6

導出(export)

ES6容許在一個模塊中使用export來導出多個變量和函數。編程

導出變量
export let varible = "test variable exprot";
export default varible;
let name = "cat";
let color = "yellow";
export {name, color}
導出常量
export const NUMBER_LENGTH = 20
導出函數
export function myModuleFn(somParams) {
    return somParams
}

導入(import)

定義好模塊的輸出,就能夠在另外一個模塊經過import導入數組

import varible from "test.js"
import {myModuleFn} from "myModuleFn";
import {name, color} from "./path/to/test.js";

4. 箭頭函數(Arrow Function)

=>不僅是function的簡寫,它還帶來了其餘好處。箭頭函數與包圍它的代碼共享同一個this,可以幫你解決this的指向問題。有經驗的javaScript開發者都熟悉var self = this或var that = this這種引用外圍的this的模式。但=>就不須要這種模式了。promise

不管是箭頭函數仍是bind,每次被執行都返回的是一個新的函數引用,所以若是你還須要函數的引用去作別的一些事(如卸載監聽器),那麼你必須保存這個引用。app

箭頭函數與普通函數的區別

  • 箭頭函數是匿名函數,不能做爲構造函數,不能使用new
  • 箭頭函數不綁定arguments,取而代之用rest參數...解決
  • 箭頭函數不綁定this,會捕獲其所在的上下文的this值,做爲本身的this值
  • 箭頭函數經過 call() 或 apply() 方法調用一個函數時,只傳入了一個參數,對 this 並無影響。
  • 箭頭函數沒有原型屬性
  • 箭頭函數不能當作Generator函數,不能使用yield關鍵字
  • 箭頭函數的 this 永遠指向其上下文的 this ,任何方法都改變不了其指向,如 call() , bind() , apply()
    普通函數的this指向調用它的那個對象

5. 模板字符串

ES6支持模板字符串,使得字符串的拼接更加簡潔、直觀。異步

  • 不使用模板字符串
var name = 'your name is ' + first + ' ' + last;
  • 使用模板字符串
var name = `your name is ${first}  ${last}`;

在ES6中經過${}就能夠完成字符串拼接,只須要將變量放在大括號中。模塊化

7. 解構賦值

解構賦值語法是Javascript的一種表達式,能夠方便的從數組或對象中快速提取值賦給定義的變量。異步編程

獲取數組的值

從數據中獲取值並賦值到的變量中,變量的順序與數組中對象順序對應

var foo = [{"a": "one"}, "two", "three", "four"];
var [one,  two, three] = foo;
console.log(one, two, three)
// 若是你要忽略某些值, 你能夠按照下面的寫法獲取你想要的值
var [first, , , last] = foo;
console.log(first, last)

var [a, b] = [1, 2]
console.log(a, b)

若是沒有從數組中獲取到值,能夠爲變量設置一個默認值。

var a ,b;
[a= 3, b=7]=[1]

獲取對象的值

const student = {
  name: "Nyan",
  age: 27,
  city: "ShenZhen"
}
const {name, age, city} = student;
console.log(name, age, city)

8. 延展操做符(Spread operator)

延展操做符...能夠在函數調用/數組構造時,將數組表達式或者string在語法層面展開;還能夠在構造對象時,將對象表達式按key-value方式展開。

語法

  • 函數調用
myFunction(...iterableObj)
  • 數組構造或字符串
[...iterableObj, '4', ...'hello', 6]
  • 構造對象時,進行克隆或屬性拷貝(ES2018)新增特性:
let objClone = {...obj};

應用場景

  • 在函數調用時使用延展操做符
function (x, y, z) {
  return x + y + z;
}
const numbers= [1, 2, 3];
console.log(sum.apply(null, numbers))
console.log(sum(...numbers))
  • 構造數組
    沒有延展操做符的時候,只能經過使用push, splice, concat等方法,來將已有的數組元素變成新數組的一部分。有了延展操做符,構造數組更加簡單,優雅。
const students = ["Jack", "Tom"];
const persons = ["Jony", ...students, "Kin", "Anny"]
console.log(persons)

和參數列表的展開相似,...在構造數組時,能夠任意位置屢次使用。

  • 數組拷貝
var arr = [1, 2, 4];
var arr2 = [...arr]
arr2.push(5)
console.log(arr2)

展開語法,與object.assign()行爲一致,執行的是都是淺拷貝(只遍歷一層)

  • 鏈接多個數組
var arr3 = [...arr1, ...arr3]
// 等同與
var arr4 = arr1.concat(arr2)

在ES2018中延展操做符增長了對對象的支持

var obj1 = {foo: "baz", x: 12};
var obj2 = {foo: "bar", y: 34};
var cloneObj = {...obj1};
var mergeObj = {...obj, ...obj2};
console.log(obj1, obj2)
  • 在React中使用
    一般咱們在封裝一個組件時,會對外公開一些props用於實現功能。大部分狀況下在外部使用都應顯示傳遞的props.可是當傳遞大量的props時,會很是繁瑣,這時咱們可使用...延展操做符,用於取出參數對象的全部可遍歷屬性,來進行傳遞
  • 通常狀況下,咱們這樣傳遞
<CustomComponent name="Nyan" age={27} />
  • 使用...,等同於上面的寫法
const params = {
  name: "name",
  age: 27
}
<CustomComponent {...params} />
  • 配合解構賦值避免傳入一些不須要的參數
const params = {
  name: "name",
  age: 27,
  type: "type Name"
  }
  var {type, ...other} = params;
<CustomComponent {...other} />

9. 對象屬性的簡寫

在ES6中容許咱們在設置一個對象的屬性的時候不指定屬性名

  • 不使用es6
const name= "name", age = 27
const student = {name: name,age: age, getName: function(){}}

對象必須包含屬性和值,顯得很是冗餘

  • 使用Es6
const name= "name", age = 27
const student = {name,age, function getName(){}}

10. Promise

Promise是異步編程的一種解決方案,比傳統的解決方案callback更加優雅。它最先由社區提出與實現,ES6將其寫進了語言標準,統一了寫法,原生提供了Promise對象。

  • 不使用ES6
setTimeout(function(){
  console.log("promise test")
  setTimeout(function(){
  console.log("promise test 1")
  }, 1000)
}, 1000)
  • 使用ES6
var waitSecond = new Promise(function(resolve, reject){
  setTimeout(resolve, 1000)
});
waitSeccond
.then(function(){
  console.log("promise test")
  return waitSecond
}).then(function(){
  console.log("promise test 1")
})
相關文章
相關標籤/搜索