前兩天,Node V4 已經(jīng)正式發(fā)布了。這是它與 io.js 合并后發(fā)布的第一個穩(wěn)定版本,其中有很多新的亮點(diǎn),添加了ES6。已經(jīng)有很多關(guān)于 ES6 的概述了,我們這篇文章將說明如何使用它們。
1. Template Strings(模版字符串)
如果你曾在 JavaScript 中試圖創(chuàng)建一個多行字符串的話,你可能是這么做的:
var message = [
'The quick brown fox',
'jumps over',
'the lazy dog'
].join('\n')
這只適用于少量的文本,當(dāng)句子比較多的時候就會顯得混亂。因此,一個聰明的開發(fā)者想出了一個下面這個叫做 multiline 的hack :
var multiline = require('multiline');
var message = multiline(function () {/*
The quick brown fox
jumps over
the lazy dog
*/});
幸運(yùn)的是,ES6 為我們帶來了模版字符串:
var message = `
The quick brown fox
jumps over
the lazy dog
`;
此外,它還給我們帶來字符串插值:
var name = 'Schroedinger';
// stop doing this ...
var message = 'Hello ' + name + ', how is your cat?';
var message = ['Hello ', name, ', how is your cat?'].join('');
var message = require('util').format('Hello %s, how is your cat?', name);
// and instead do that ...
var message = `Hello ${name}, how is your cat?`;
在 MDN 上查看關(guān)于 模版字符串 的細(xì)節(jié)
2. Classes(類)
ES5 中定義類看起來有些奇怪,并且需要花費(fèi)一定的時間:
var Pet = function (name) {
this._name = name;
};
Pet.prototype.sayHello = function () {
console.log('*scratch*');
};
Object.defineProperty(Pet.prototype, 'name', {
get: function () {
return this._name;
}
});
var Cat = function (name) {
Pet.call(this, name);
};
require('util').inherits(Cat, Pet);
Cat.prototype.sayHello = function () {
Pet.prototype.sayHello.call(this);
console.log('miaaaauw');
};
幸運(yùn)的是,我們現(xiàn)在可以在 Node 中使用 ES6 語法:
class Pet {
constructor(name) {
this._name = name;
}
sayHello() {
console.log('*scratch*');
}
get name() {
return this._name;
}
}
class Cat extends Pet {
constructor(name) {
super(name);
}
sayHello() {
super.sayHello();
console.log('miaaaauw');
}
}
擴(kuò)展關(guān)鍵字,構(gòu)造函數(shù),調(diào)用超級類和屬性,是不是非常棒?更多內(nèi)容,請查看 MDN 綜合指南。
3. Arrow Functions(箭頭函數(shù))
函數(shù)中動態(tài)綁定的 this 經(jīng)常會導(dǎo)致一些混亂,人們一般會使用以下方式:
Cat.prototype.notifyListeners = function () {
var self = this;
this._listeners.forEach(function (listener) {
self.notifyListener(listener);
});
};
// OR
Cat.prototype.notifyListeners = function () {
this._listeners.forEach(function (listener) {
this.notifyListener(listener);
}.bind(this));
};
而現(xiàn)在,你可以直接使用箭頭函數(shù):
Cat.prototype.notifyListeners = function () {
this._listeners.forEach((listener) => {
this.notifyListener(listener);
});
};
查看更多有關(guān) 箭頭函數(shù) 的詳細(xì)信息
4. Object Literals
通過 object literals,你可以使用如下快捷方式:
var age = 10, name = 'Petsy', size = 32;
// instead of this ...
var cat = {
age: age,
name: name,
size: size
};
// ... do this ...
var cat = {
age,
name,
size
};
此外,你還可以自己輕松的為 object literals 添加函數(shù)。
5. Promises
不再需要依賴第三方的庫如 bluebird 或者 Q,你可以使用本地 Promises。有下面這樣公開的 API:
var p1 = new Promise(function (resolve, reject) {});
var p2 = Promise.resolve(20);
var p3 = Promise.reject(new Error());
var p4 = Promise.all(p1, p2);
var p5 = Promise.race(p1, p2);
// and obviously
p1.then(() => {}).catch(() => {});
6. String Methods
也有一些新的字符串方法:
// replace `indexOf()` in a number of cases
name.startsWith('a')
name.endsWith('c');
name.includes('b');
// repeat the string three times
name.repeat(3);
去告訴那些使用 Ruby 的孩子!另外,對 Unicode字符串 的處理也更加好了。
7. let and const
猜測下列函數(shù)調(diào)用的返回值:
var x = 20;
(function () {
if (x === 20) {
var x = 30;
}
return x;
}()); // -> undefined
Yep, undefined. Replace var with let and you get the expected behaviour:
let x = 20;
(function () {
if (x === 20) {
let x = 30;
}
return x;
}()); // -> 20
原因:var 是函數(shù)作用域,而 let 是塊作用域(正如大部分人期待的那樣)。因此我們可以說, let 是 var 的變種。你可以在 MDN 獲取更多詳細(xì)信息。
彩蛋:Node 現(xiàn)在也支持 const 關(guān)鍵字了,它可以防止你為相同的參考賦予不同的值。
var MY_CONST = 42; // no, no const MY_CONST = 42; // yes, yes MY_CONST = 10 // with const, this is no longer possible
總結(jié)
Node V4 帶來的 ES6 功能遠(yuǎn)不止這些,但我希望這七個例子已經(jīng)能夠說服你更新并使用新的版本。
還有很多其他的特性(如 maps/sets,、symbols 以及 generators 等)。請確保你已經(jīng)看過 Node 中關(guān)于 ES6 的概述。愉快的升級吧~
via:cli-nerd,本文由 Specs 翻譯整理,發(fā)布在 WEB資源網(wǎng),轉(zhuǎn)載請注明來源。
哈爾濱品用軟件有限公司致力于為哈爾濱的中小企業(yè)制作大氣、美觀的優(yōu)秀網(wǎng)站,并且能夠搭建符合百度排名規(guī)范的網(wǎng)站基底,使您的網(wǎng)站無需額外費(fèi)用,即可穩(wěn)步提升排名至首頁。歡迎體驗(yàn)最佳的哈爾濱網(wǎng)站建設(shè)。
