码迷,mamicode.com
首页 > 其他好文 > 详细

ES6新特性

时间:2019-12-14 09:30:59      阅读:90      评论:0      收藏:0      [点我收藏+]

标签:outlook   组合   默认   新特性   json   也有   cal   lan   first   

ES6是什么?

实际上, 它是一种新的javascript规范。

 

下面就是一个简单的JavaScript发展时间轴:

1、1995:JavaScript诞生,它的初始名叫LiveScript。

2、1997:ECMAScript标准确立。

3、1999:ES3出现,与此同时IE5风靡一时。

4、2000–2005: XMLHttpRequest又名AJAX, 在Outlook Web Access (2000)、Oddpost (2002),Gmail (2004)和Google Maps (2005)大受重用。

5、2009: ES5出现,(就是我们大多数人现在使用的)例如foreach,Object.keys,Object.create和JSON标准。

6、2015:ES6/ECMAScript2015出现。

 

1.Default Parameters(默认参数) in ES6

还记得我们以前(ES5)不得不通过下面方式来定义默认参数:

 

var link = function (height, color, url) {
 
var height = height || 50;
 
var color = color || ‘red‘;
 
}

 

但在ES6,我们可以直接把默认值放在函数申明里:

var link = function(height = 50, color = ‘red‘, url = ‘http://azat.co‘) {
 
...
 
}

 

2.Template Literals(模板对象) in ES6

在其它语言中,使用模板和插入值是在字符串里面输出变量的一种方式。

因此,在ES5,我们可以这样组合一个字符串:

var name = ‘Your name is ‘ + first + ‘ ‘ + last + ‘.‘;
 
var url = ‘http://localhost:3000/api/messages/‘ + id;

 

幸运的是,在ES6中,我们可以使用新的语法$ {NAME},并把它放在反引号里:

var name = `Your name is ${first} ${last}. `;
 
var url = `http://localhost:3000/api/messages/${id}`;

 

3.Multi-line Strings (多行字符串)in ES6

ES6的多行字符串是一个非常实用的功能。

在ES5中,我们不得不使用以下方法来表示多行字符串:

 

var roadPoem = ‘Then took the other, as just as fair,nt‘
 
+ ‘And having perhaps the better claimnt‘
 
+ ‘Because it was grassy and wanted wear,nt‘
 
+ ‘Though as for that the passing therent‘
 
+ ‘Had worn them really about the same,nt‘;
 
 
 
var fourAgreements = ‘You have the right to be you.n
 
You can only be you when you do your best.;
 

 

然而在ES6中,仅仅用反引号就可以解决了:

var roadPoem = `Then took the other, as just as fair,
 
And having perhaps the better claim
 
Because it was grassy and wanted wear,
 
Though as for that the passing there
 
Had worn them really about the same,`;
 
 
 
var fourAgreements = `You have the right to be you.
 
You can only be you when you do your best.`;

 

 

4.Destructuring Assignment (解构赋值)in ES6

解构可能是一个比较难以掌握的概念。先从一个简单的赋值讲起,其中house 和 mouse是key,同时house 和mouse也是一个变量,

在ES5中是这样:

// data has properties house and mouse
 
var data = $(‘body‘).data();
 
var house = data.house,
 
var mouse = data.mouse;

 

以及在node.js中用ES5是这样:

var jsonMiddleware = require(‘body-parser‘).jsonMiddleware ;
 
// body has username and password
 
var body = req.body;
 
var username = body.username,
 
var password = body.password;

 

 

在ES6,我们可以使用这些语句代替上面的ES5代码:

// we‘ll get house and mouse variables
 
var { house, mouse } = $(‘body‘).data();
 
var { jsonMiddleware } = require(‘body-parser‘);
 
var { username, password } = req.body;
 

 

这个同样也适用于数组,非常赞的用法:

var [col1, col2] = $(‘.column‘);
 
var [line1, line2, line3, , line5] = file.split(‘n‘);

 

我们可能需要一些时间来习惯解构赋值语法的使用,但是它确实能给我们带来许多意外的收获。

5.Enhanced Object Literals (增强的对象字面量)in ES6

使用对象文本可以做许多让人意想不到的事情!通过ES6,我们可以把ES5中的JSON变得更加接近于一个类。

下面是一个典型ES5对象文本,里面有一些方法和属性:

 

 
var serviceBase = {
 
port: 3000,
 
url: ‘azat.co‘,
 
};
 
var getAccounts = function() {
 
return [1,2,3];
 
};
 
var accountServiceES5 = {
 
port: serviceBase.port,
 
url: serviceBase.url,
 
getAccounts: getAccounts,
 
toString: function() {
 
return JSON.stringify(this.valueOf());
 
},
 
getUrl: function() {
 
return "http://" + this.url + ‘:‘ + this.port;
 
},
 
valueOf_1_2_3: getAccounts(),
 
}

 

如果我们想让它更有意思,我们可以用Object.create从serviceBase继承原型的方法:

 

var accountServiceES5ObjectCreate = Object.create(serviceBase);
 
var accountServiceES5ObjectCreate = {
 
getAccounts: getAccounts,
 
toString: function() {
 
return JSON.stringify(this.valueOf());
 
},
 
getUrl: function() {
 
return ‘http://‘ + this.url + ‘:‘ + this.port;
 
},
 
valueOf_1_2_3: getAccounts(),
 
}

 

6.Arrow Functions in(箭头函数) ES6

这是我迫不及待想讲的一个特征,CoffeeScript 就是因为它丰富的箭头函数让很多开发者喜爱。在ES6中,也有了丰富的箭头函数。

这些丰富的箭头是令人惊讶的因为它们将使许多操作变成现实,比如:

以前我们使用闭包,this总是预期之外地产生改变,而箭头函数的迷人之处在于,现在你的this可以按照你的预期使用了,身处箭头函数里面,this还是原来的this。

有了箭头函数在ES6中, 我们就不必用that = this或 self =  this  或 _this = this  或.bind(this)。

例如,下面的代码用ES5就不是很优雅:

var _this = this;
 
$(‘.btn‘).click(function(event) {
 
_this.sendData();
 
});

 

在ES6中就不需要用 _this = this:

$(‘.btn‘).click((event) => {
 
this.sendData();
 
});

 

不幸的是,ES6委员会决定,以前的function的传递方式也是一个很好的方案,所以它们仍然保留了以前的功能。

下面这是一个另外的例子,我们通过call传递文本给logUpperCase() 函数在ES5中:

 

var logUpperCase = function() {
 
var _this = this;
 
 
 
this.string = this.string.toUpperCase();
 
return function () {
 
return console.log(_this.string);
 
}
 
};
 
 
 
logUpperCase.call({ string: ‘ES6 rocks‘ })();

 

而在ES6,我们并不需要用_this浪费时间:

var logUpperCase = function() {
 
this.string = this.string.toUpperCase();
 
return () => console.log(this.string);
 
};
 
 
 
logUpperCase.call({ string: ‘ES6 rocks‘ })();

 

7. Promises in ES6

Promises 是一个有争议的话题。因此有许多略微不同的promise 实现语法。Q,bluebird,deferred.js,vow, avow, jquery 一些可以列出名字的。

也有人说我们不需要promises,仅仅使用异步,生成器,回调等就够了。但令人高兴的是,在ES6中有标准的Promise实现。

下面是一个简单的用setTimeout()实现的异步延迟加载函数:

 

setTimeout(function() {
 
console.log(‘Yay!‘);
 
}, 1000);

 

在ES6中,我们可以用promise重写:

var wait1000 = new Promise(function(resolve, reject) {
 
setTimeout(resolve, 1000);
 
}).then(function() {
 
console.log(‘Yay!‘);
 
});

 

 

或者用ES6的箭头函数:

var wait1000 = new Promise((resolve, reject)=> {
 
setTimeout(resolve, 1000);
 
}).then(()=> {
 
console.log(‘Yay!‘);
 
});

 

8.Block-Scoped Constructs Let and Const(块作用域和构造let和const)

在ES6代码中,你可能已经看到那熟悉的身影let。在ES6里let并不是一个花俏的特性,它是更复杂的。

Let是一种新的变量申明方式,它允许你把变量作用域控制在块级里面。我们用大括号定义代码块,在ES5中,块级作用域起不了任何作用:

function calculateTotalAmount (vip) {
 
var amount = 0;
 
if (vip) {
 
var amount = 1;
 
}
 
 
 
// more crazy blocks!
 
{
 
var amount = 100;
 
{
 
var amount = 1000;
 
}
 
}
 
 
 
return amount;
 
}
 
 
 
console.log(calculateTotalAmount(true));

 

 

结果将返回1000,这真是一个bug。

在ES6中,我们用let限制块级作用域。而var是限制函数作用域。

 

function calculateTotalAmount (vip) {
 
 
 
// probably should also be let, but you can mix var and let
 
var amount = 0;
 
if (vip) {
 
 
 
// first amount is still 0
 
let amount = 1;
 
}
 
 
 
// more crazy blocks!
 
{
 
// first amount is still 0
 
let amount = 100;
 
{
 
 
 
// first amount is still 0
 
let amount = 1000;
 
}
 
}
 
 
 
return amount;
 
}
 
 
 
console.log(calculateTotalAmount(true));

 

 

这个结果将会是0,因为块作用域中有了let。如果(amount=1).那么这个表达式将返回1。谈到const,就更加容易了;

它就是一个不变量,也是块级作用域就像let一样。

下面是一个演示,这里有一堆常量,它们互不影响,因为它们属于不同的块级作用域:

 

function calculateTotalAmount (vip) {
 
const amount = 0;
 
if (vip) {
 
const amount = 1;
 
}
 
 
 
// more crazy blocks!
 
{
 
const amount = 100 ;
 
{
 
const amount = 1000;
 
}
 
}
 
 
 
return amount;
 
}
 
 
 
console.log(calculateTotalAmount(true));

 

 

从我个人看来,let 和const使这个语言变复杂了。没有它们的话,我们只需考虑一种方式,现在有许多种场景需要考虑。

 

ES6新特性

标签:outlook   组合   默认   新特性   json   也有   cal   lan   first   

原文地址:https://www.cnblogs.com/liangyaofeng/p/10526035.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!