ES6常用的新特性

weixin_33890499發表於2017-09-02

1、設定預設引數(default parameters)
先回顧一下之前是怎麼定義預設引數的:

var link = function (height, color, url) {

    var height = height || 50;

    var color = color || 'red';

    var url = url || 'http://azat.co';

    ...

}

在ES6中,我們可以這樣來設定預設的引數:


var link = function(height = 50, color = 'red', url = 'http://azat.co') {

  ...

}

2、模板物件(template literals)
之前我們是這樣拼接字串和變數的:


var name = 'Your name is ' + first + ' ' + last + '.';

var url = 'http://localhost:3000/api/messages/' + id;

在ES6中為我們提供了${ } 的方式,我們可以直接將變數寫在花括號裡:

var name = `Your name is ${first} ${last}. `;

var url = `http://localhost:3000/api/messages/${id}`;

3、多行字串
在ES5中:


var roadPoem = 'Then took the other, as just as fair,nt'

    + 'And having perhaps the better claimnt'

    + 'Because it was grassy and wanted wear,nt'

    + 'Though as for that the passing therent'

    + 'Had worn them really about the same,nt';

var fourAgreements = 'You have the right to be you.n

    You can only be you when you do your best.';

而在ES6中,我們使用反引號就可以解決了:

var roadPoem = `Then took the other, as just as fair,

    And having perhaps the better claim

    Because it was grassy and wanted wear,

    Though as for that the passing there

    Had worn them really about the same,`;

var fourAgreements = `You have the right to be you.

    You can only be you when you do your best.`;

4、解構賦值
即當鍵值對的鍵和值名字相同時,我們可以寫一個就可以了。

5、class類的概念
ES6中增加了類的概念,其實ES5中已經可以實現類的功能了,只不過使用Class實現可以更加清晰,更像物件導向的寫法。

class Animal {
  constructor(){
    console.log('我是一個動物');
  }
}

class Person extends Animal {
  constructor(){
    super();
    console.log('我是一個程式設計師');
  }
}

let aa = new Person();
//我是一個動物
//我是一個程式設計師

ES6 新語法

1、箭頭函式

ES6中可以使用 => 作為函式表達形式,極簡風格,引數+ => +函式體。
如:

var foo = function(){return 1;};
//等價於
let foo = () => 1;

值得注意的是,箭頭函式的this的指向的問題,它不是指向window而是指向物件本身

function aa(){
  this.bb = 1;
  setTimeout(() => {
    this.bb++; //this指向aa
    console.log(this.bb);
  },500);
}

aa(); //2
2、let和const宣告變數

在JS中,是沒有塊級作用域的概念的,而let可以起到這一效果。如,在花括號裡宣告只在花括號裡有效;

{
  let a = 1;
  var b = 2;
}
console.log(b); // 2
console.log(a); // a is not defind

在JS中變數和函式的宣告會提升到當前作用域最頂部執行,這樣會出現問題,如在for迴圈時;

var a = [];
//函式和變數i會最先進行宣告,同時全域性變數i經過for迴圈賦值為10
for (var i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
console.log(i);//10
a[6]();//10

而let則不會:

for (let i = 0; i < 10; i++) {
  a[i] = function () {
    console.log(i);
  };
}
a[6](); //6

let也不會有變數提升:

console.log(a); // a is not defined
let a = 1;

let也不會允許在同一塊級作用域中宣告兩個同名變數,宣告會報錯。

const(constant 常數的意思)
const也是用來宣告一個變數,並且宣告的為一個常量,宣告之後不能修改。和let一樣,只能在一個塊級作用域中宣告一個同名變數,且只在這個塊級作業域中有效。

const PI = 3.1415;
console.log(PI); // 3.1415
//PI = 3; // Assignment to constant variable.(不能給常量賦值)
//const PI = 3.1;// Identifier 'PI' has already been declared

相關文章