如果你曾在 JavaScript 中试图创建一个多行字符串的话,你可能是这么做的:var message = ["The quick brown fox","jumps over","the lazy dog"].join("
")这只适用于少量的文本,当句子比较多的时候就会显得混乱。因此,一个聪明的开发者想出了一个下面这个叫做 multiline 的hack :var multiline = require("multiline");var message = multiline(function () {/*The quick brown foxjumps overthe lazy dog*/});幸运的是,ES6 为我们带来了模版字符串:var message = `The quick brown foxjumps overthe 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 上查看关于 模版字符串 的细节
2. Classes(类)
ES5 中定义类看起来有些奇怪,并且需要花费一定的时间: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");};幸运的是,我们现在可以在 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");}}扩展关键字,构造函数,调用超级类和属性,是不是非常棒?更多内容,请查看 MDN 综合指南。
3. Arrow Functions(箭头函数)
函数中动态绑定的 this 经常会导致一些混乱,人们一般会使用以下方式:Cat.prototype.notifyListeners = function () {var self = this;this._listeners.forEach(function (listener) {self.notifyListener(listener);});};// ORCat.prototype.notifyListeners = function () {this._listeners.forEach(function (listener) {this.notifyListener(listener);}.bind(this));};而现在,你可以直接使用箭头函数:Cat.prototype.notifyListeners = function () {this._listeners.forEach((listener) => {this.notifyListener(listener);});};查看更多有关 箭头函数 的详细信息
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 添加函数。
也有一些新的字符串方法:// replace `indexOf()` in a number of casesname.startsWith("a")name.endsWith("c");name.includes("b");// repeat the string three timesname.repeat(3);去告诉那些使用 Ruby 的孩子!另外,对 Unicode字符串 的处理也更加好了。
7. let and const
猜测下列函数调用的返回值:var x = 20;(function () {if (x === 20) {var x = 30;}return x;}()); // -> undefinedYep, 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 是函数作用域,而 let 是块作用域(正如大部分人期待的那样)。因此我们可以说, let 是 var 的变种。你可以在 MDN 获取更多详细信息。彩蛋:Node 现在也支持 const 关键字了,它可以防止你为相同的参考赋予不同的值。var MY_CONST = 42; // no, noconst MY_CONST = 42; // yes, yesMY_CONST = 10 // with const, this is no longer possible