首頁  >  文章  >  web前端  >  JS之--ES 2015/6 新特性匯總

JS之--ES 2015/6 新特性匯總

怪我咯
怪我咯原創
2017-06-26 12:01:29984瀏覽

ES 2015/6 新增內容還是比較多的,這裡僅大綱性的列舉一下(不一定全面)這些特性。其實,每個點挖進去都會有很多學問在裡頭,本文旨在匯總,所以不對這些特性進行深層的討論及研究。隨後若有時間,再單獨寫幾篇部落格對常用的點進行深挖,與大家進行深度交流。

箭頭函數

箭頭函數,透過 => 語法實作的函數簡寫形式,C#/JAVA8/CoffeeScript 都有類似語法。與函數不同,箭頭函數與其執行下文環境共用同一個 this。如果一個箭頭函數出現在函數物件內部,它會與這個函數共用 arguments 變數。


// Expression bodiesvar odds = evens.map(v => v + 1);var nums = evens.map((v, i) => v + i);// Statement bodiesnums.forEach(v => {
  if (v % 5 === 0)    fives.push(v);});// Lexical thisvar bob = {
  _name: "Bob",
  _friends: ['jim'],
  printFriends() {
    this._friends.forEach(f =>
      console.log(this._name + " knows " + f)); // Bob knows jim
  }};// Lexical argumentsfunction square() {
  let example = () => {
    let numbers = [];
    for (let number of arguments) {
      numbers.push(number * number);
    }

    return numbers;
  };

  return example();}square(2, 4, 7.5, 8, 11.5, 21); // returns: [4, 16, 56.25, 64, 132.25, 441]


類別Class

Javascript 類別 並不是引進了一個新的物件導向的物件繼承模型,而是基於原型繼承的語法糖。其提供了一個更簡單和清晰的語法來創建物件並處理繼承。


class Rectangle {
  constructor(height, width) {
    this.height = height;
    this.width = width;
  }}


類別沒有宣告提升,必須確保在呼叫前已經進行了宣告。

建構子 constructor 是一個特殊的方法,其用於建立和初始化類別的實例。

靜態方法static 關鍵字用於聲明靜態方法

建立子類別extends 關鍵字用於建立子類,這裡要注意: extends 不能用來擴充常規物件(不可建構/非建構的),如果要繼承常規對象,可使用Object.setPrototypeOf()

呼叫超類別super 關鍵字可以用來呼叫父類別中的方法

Mix-ins 混合

增強的物件字面量

透過字面量形式可以實現,定義prototype、鍵值對簡寫、定義方法等、動態屬性名稱。


var obj = {
    // Sets the prototype. "__proto__" or '__proto__' would also work.
    __proto__: theProtoObj,
    // Computed property name does not set prototype or trigger early error for
    // duplicate __proto__ properties.
    ['__proto__']: somethingElse,
    // Shorthand for ‘handler: handler’
    handler,
    // Methods
    toString() {
     // Super calls
     return "d " + super.toString();
    },
    // Computed (dynamic) property names
    [ "prop_" + (() => 42)() ]: 42};


模板字串

模板字串提供建構字串的語法糖,在Prel/python 等語言中也都有類似特性。


// Basic literal string creation
`This is a pretty little template string.`

// Multiline strings
`In ES5 this is
 not legal.`

// Interpolate variable bindings
var name = "Bob", time = "today";
`Hello ${name}, how are you ${time}?`

// Unescaped template strings
String.raw`In ES5 "\n" is a line-feed.`

// Construct an HTTP request prefix is used to interpret the replacements and construction
GET`http://foo.org/bar?a=${a}&b=${b}
    Content-Type: application/json
    X-Credentials: ${credentials}
    { "foo": ${foo},
      "bar": ${bar}}`(myOnReadyStateChangeHandler);

解構賦值

Destructuring 法是一個Javascript表達式,這使得可以將值從陣列或屬性從物件提取到不同的變數中。

// list matching
var [a, ,b] = [1,2,3];
a === 1;
b === 3;

// object matching (用新变量名赋值)
var { op: a, lhs: { op: b }, rhs: c }
       = getASTNode()

// object matching shorthand
// binds `op`, `lhs` and `rhs` in scope
var {op, lhs, rhs} = getASTNode()

// Can be used in parameter position
function g({name: x}) {
  console.log(x);
}
g({name: 5})

// Fail-soft destructuring
var [a] = [];
a === undefined;

// Fail-soft destructuring with defaults
var [a = 1] = [];
a === 1;

// 变量可以先赋予默认值。当要提取的对象没有对应的属性,变量就被赋予默认值。
var {a = 10, b = 5} = {a: 3};
console.log(a); // 3
console.log(b); // 5

// Destructuring + defaults arguments
function r({x, y, w = 10, h = 10}) {
  return x + y + w + h;
}
r({x:1, y:2}) === 23

// 对象属性计算名和解构
let key = "z";
let { [key]: foo } = { z: "bar" };

console.log(foo); // "bar"

Default + Rest + Spread

為函數參數提供預設值& ... 定數量參數

function f(x, y=12) {
  // y is 12 if not passed (or passed as undefined)
  return x + y;
}
f(3) == 15


function f(x, ...y) {
  // y is an Array
  return x * y.length;
}
f(3, "hello", true) == 6



function f(x, y, z) {
  return x + y + z;
}
// Pass each elem of array as argument
f(...[1,2,3]) == 6

Let + Const

let 用來宣告區塊層級作用域變數。 const 用來宣告常數。

function f() {
  {
    let x;
    {
      // this is ok since it's a block scoped name
      const x = "sneaky";
      // error, was just defined with `const` above
      x = "foo";
    }
    // this is ok since it was declared with `let`
    x = "bar";
    // error, already declared above in this block
    let x = "inner";
  }
}

迭代器

透過 symbol.iterator 可建立自訂迭代器。

let fibonacci = {
  [Symbol.iterator]() {
    let pre = 0, cur = 1;
    return {
      next() {
        [pre, cur] = [cur, pre + cur];
        return { done: false, value: cur }
      }
    }
  }
}

for (var n of fibonacci) {
  // truncate the sequence at 1000
  if (n > 1000)
    break;
  console.log(n);
}


生成器 Generators

普通函數使用function聲明,而生成器函數使用function*聲明。

在生成函數內部,有一種類似return的語法:關鍵字yield。二者的差別是,普通函數只可以return一次,而生成器函數可以yield多次(當然也可以只yield一次)。在生成器的執行過程中,遇到yield表達式立即暫停,後續可恢復執行狀態。

function* quips(name) {
  yield "你好 " + name + "!";
  yield "希望你能喜欢这篇介绍ES6的译文";
  if (name.startsWith("X")) {
    yield "你的名字 " + name + "  首字母是X,这很酷!";
  }
  yield "我们下次再见!";
}

Unicode

// same as ES5.1
"

以上是JS之--ES 2015/6 新特性匯總的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn