ES6,官方名称是ECMAScript2015,不过名字ES6更简洁。ES6不再是JavaScript开发的标准,但它已经广泛应用于编程实践中。如果你还没有使用过ES6,现在还不算太晚......这里有10个突出的ES6特性,排名不分先后:函数参数默认值模板字符串多行字符串模块化与Const类1.函数参数默认值不使用ES6设置函数参数的默认值:functionfoo(height,color){varheight=height||50;varcolor=color||'red';//...}这样写一般没问题,但是当参数的布尔值为false,会出事!例如,我们这样调用foo函数:foo(0,"","")因为0的布尔值是false,所以height的值将是50。同样,color的值是'red'。使用ES6functionfoo(height=50,color='red'){//...}2.模板字符串不要使用ES6使用+号将变量拼接成字符串:varname='Yournameis'+first+''+last+'.'用ES6把变量放在大括号里:varname=`Yournameis${first}${last}.`ES6写的更简洁直观。3、多行字符串不使用ES6,使用“nt”将多行字符串拼接在一起:,\n\t'+'Thoughasforthatthepassingthere\n\t'+'Hadwornthemreallyaboutthesame,\n\t'使用ES6在反引号之间放置多行字符串``就好了:varroadPoem=`Thentooktheother,asjustasfair,AndhavingperhapsthebetterclaimBecauseitwasgrassyandwantedwear,Thoughasforthatthepassingthereallythem`4.解构赋值不使用ES6。当需要获取对象的属性值时,需要单独获取:vardata=$('body').data();//data有house和mouse属性varhouse=data.house;varmouse=data.老鼠;使用ES6一次性获取对象的子属性:var{house,mouse}=$('body').data()对于数组也是一样:var[col1,col2]=$('.column');5.对象属性简写没有使用ES6对象必须包含属性和值,非常多余:varbar='bar';varfoo=function(){//...}varbaz={bar:bar,foo:foo};直接在ES6对象中写变量很简单:varbar='bar';varfoo=function(){//...}varbaz={bar,foo};6.箭头函数不使用ES6普通函数体this,指向被调用的对象。functionfoo(){console.log(this.id);}varid=1;foo();//Output1foo.call({id:2});//Output2在ES6箭头函数体中使用了this,其中是定义调用它的对象,而不是它被调用的对象。varfoo=()=>{console.log(this.id);}varid=1;foo();//输出1foo.call({id:2});//输出17.Promise没有使用ES6嵌套两个setTimeout回调函数:setTimeout(function(){console.log('Hello');//1秒后输出“Hello”setTimeout(function(){console.log('Fundebug');//2秒后输出"Fundebug"},1000);},1000);使用ES6使用两个then是异步编程序列化,避免回调地狱:varwait1000=newPromise(function(resolve,reject){setTimeout(resolve,1000);});wait1000.then(function(){console.log("Hello");//1秒后输出"Hello"returnwait1000;}).then(function(){console.log("Fundebug");//2秒后输出"Fundebug"});8.Let和Const使用Varvar定义的变量没有函数级作用域:{vara=10;}console.log(a);//输出10let和constlet定义的变量是块级作用域,所以会报错报错:(如果你想实时监控JavaScript应用错误,欢迎免费使用Fundebug){leta=10;}console.log(a);//Error"ReferenceError:aisnotdefined"constandLikelet,it也是块级范围的。9.类不使用ES6使用构造函数创建对象:functionPoint(x,y){this.x=x;this.y=y;this.add=function(){returnthis.x+this.y;};}varp=newPoint(1,2);console.log(p.add());//输出3使用ES6定义类使用Class,更加规范,可以继承:classPoint{constructor(x,y){这个。x=x;this.y=y;}add(){returnthis.x+this.y;}}varp=newPoint(1,2);console.log(p.add());//输出310。模块化JavaScript一直没有官方的模块化解决方案,开发者在实践中主要使用CommonJS和AMD规范。而ES6制定了模块(Module)功能。不使用ES6Node.js,使用CommenJS规范实现模块化,前端也可以使用,但部署时需要用Browserify等工具打包。这里不妨介绍一下CommenJS规范。在module.js中,使用module.exports导出端口变量和getAccounts函数:module.exports={port:3000,getAccounts:function(){...}}在main.js中,使用require导入module.js:varservice=require('module.js')console.log(service.port)//输出3000使用ES6中的export和import关键字实现模块化。在module.js中使用export导出端口变量和getAccounts函数:exportvarport=3000exportfunctiongetAccounts(url){...}在main.js中使用import导入module.js,可以指定需要的变量imported:import{port,getAccounts}from'module'console.log(port)//输出3000也可以导入所有变量:import*asservicefrom'module'console.log(service.port)//3000
