Node.js4.0.0已经发布。这是与io.js合并后的最新稳定版,带来了一系列的新特性,支持ES6的大部分特性。ES6的特性已经有很多介绍了,这里介绍一下如何使用。1.模板字符串如果您在JavaScript中创建多行字符串,您可能会使用以下语法:varmessage=['Thequickbrownfox','jumpsover','thelazydog'].join('\n');这对于少量的字符串很好,但如果有很多则很乱。然而,一个聪明的开发者想出了一个叫做multiline的技巧:varmultiline=require('multiline');varmessage=multiline(function(){/*敏捷的棕色狐狸跳过懒惰的狗*/});幸运的是,ES6为我们带来了模板字符串:varmessage=`Thequickbrownfoxjumpsoverthelazydog`;此外,它还为我们带来了字符串插值:varname='Schroedinger';//Don'tdothis...varmessage='Hello'+name+',howisyourcat?';varmessage=['Hello',name,',howisyourcat?'].join('');varmessage=require('util').format('Hello%s,howisyourcat?',name);//shoulddoit...varmessage=`你好${name},你的猫怎么样?`;请参阅MDN上的模板字符串详细信息。2.类在ES5中定义类看起来有点奇怪和麻烦:varPet=function(name){this._name=name;};Pet.prototype.sayHello=function(){console.log('*scratch*');};Object.defineProperty(Pet.prototype,'name',{get:function(){returnthis._name;}});varCat=function(name){Pet.call(this,name);};require('util').inherits(Cat,Pet);Cat.prototype.sayHello=function(){Pet.prototype.sayHello.call(this);console.log('miaaaauw');};幸运的是,Node.js中提供了新的ES6格式:classPet{constructor(name){this._name=name;}sayHello(){console.log('*scratch*');}getname(){返回this._name;}}classCatextendsPet{constructor(name){super(name);}sayHello(){super.sayHello();console.log('miaaaauw');}}拥有extends关键字、构造函数、对超类的调用和属性不是很好吗?不止于此,看MDN上更详细的介绍3.箭头函数在函数中动态绑定到this,总会引起一些混乱。人们通常这样使用它:Cat.prototype.notifyListeners=function(){varself=this;this._listeners.forEach(function(listener){self.notifyListener(listener);});};Cat.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.对象字面量有了对象字面量,你现在有了漂亮的捷径:varage=10,name='Petsy',size=32;//不要这样做...varcat={age:age,name:name,size:size};//...改为这样做...varcat={age,name,size};此外,您现在可以轻松地向对象字面量添加函数。5.Promise不再需要依赖bluebird、Q等第三方库,可以使用原生的promises。它们公开了以下API:varp1=newPromise(function(resolve,reject){});varp2=Promise.resolve(20);varp3=Promise.reject(newError());varp4=Promise.all(p1,p2);varp5=Promise.race(p1,p2);//显然p1.then(()=>{}).catch(()=>{});6.字符串方法我们还有一堆新的字符串函数://在某些情况下可以替换`indexOf()`name.startsWith('a')name.endsWith('c');name.includes('b');//重复字符串三次name.repeat(3);去告诉Ruby的家伙们!字符串现在也有更好的unicode支持。7.let和const猜测以下函数调用的返回值:varx=20;(function(){if(x===20){varx=30;}returnx;}());//->undefined是的,未定义。使用let而不是var,你会得到预期的行为:letx=20;(function(){if(x===20){letx=30;}returnx;}());//->20是什么原因?var是函数作用域,而let是块作用域(正如大多数人所期望的那样)。所以,假设let是一个新的变量。您可以在MDN上阅读更多详细信息。另外,Node.js还支持const关键字,防止你对同一个引用赋不同的值:varMY_CONST=42;//不,noconstMY_CONST=42;//yes,yesMY_CONST=10//usedconst,这还不够EpilogueNode.js4.0.0带来了更多的ES6特性,我希望这七个例子能吸引你升级到最新版本。还有更多的语言特性(例如映射/集合、符号和生成器,这里仅举几例)。您可以查看Node.js4.0.0的ES6概述。现在升级!原文:http://www.cli-nerd.com/2015/09/09/7-reasons-to-upgrade-to-node-v4-now.html作者:DamienKlinnert翻译:LCTThttps://linux.cn/article-6212-1.html译者:wxy