ES6的新属性,深入浅出,玩转ECMAScript
既然终究要开始,为什么不是此刻???
ECMAScript 的前世今生
-1995年:JavaScript以LiveScript之名诞生
-1997年:ECMAScript标准确立
-1999年:ES3发布,IE5非常生气
-2000年-2005年:XMLHttpRequest,熟知为AJAX,在如Outlook Web Access(2002)、Oddpost(2002)、Gmail(2004)、Google Maps(2005)中得到了广泛的应用
-2009年:ES5发布(这是我们目前用的最多的版本),带来了forEach / Object.keys / Object.create(特地为Douglas Crockford所造,JSON标准创建者) ,还有JSON标准。
ECMAScript 基础
首先让我们开始对 ECMAScript 的保留字,关键字有一定的了解。
ECMAScript 保留字,关键字:
保留字 | 关键字 |
---|---|
abstract | break |
boolean | case |
Pipe | catch |
byte | continue |
char | default |
class | delete |
const | do |
debugger | else |
double | finally |
enum | for |
export | function |
extends | if |
final | in |
float | instanceof |
goto | new |
implements | return |
import | switch |
int | this |
interface | throw |
long | try |
native | typeof |
package | var |
private | void |
protected | while |
public | with |
short | |
static | |
super | |
synchronized | |
throws | |
transient | |
volatile |
ECMAScript示例
为了更直观的表达,我们将ES6 与 ES5(或更早)对比。
No1.(块级作用域的let和const)
先来看 var
function calculateTotalAmount (vip) {
var amount = 0
if (vip) {
var amount = 1
}
{ // 让块来的更疯狂
var amount = 100
{
var amount = 1000
}
}
return amount
}
console.log(calculateTotalAmount(true))
//运行结果将会是1000
再来看 let
function calculateTotalAmount (vip) {
var amount = 0 // 或许应该用let, 但你可以混用
if (vip) {
let amount = 1 // 第一个数量为 0
}
{ // 更多的块
let amount = 100 // 第一个数量为 0
{
let amount = 1000 // 第一个数量为 0
}
}
return amount
}
console.log(calculateTotalAmount(true))
//运行结果是0,因为在if块中也有let。如果什么都没有的话(amount=1),那么结果将会是1。
最后我们看 const
function calculateTotalAmount (vip) {
const amount = 0
if (vip) {
const amount = 1
}
{ // 更多的块
const amount = 100
{
const amount = 1000
}
}
return amount
}
console.log(calculateTotalAmount(true))
//个人感觉 const 是一个突破,结果是啥自己心里还没有X数嘛 0.0
No2.(定义默认参数)
定义默认参数(以前)
var link = function(height,color,ulr){
var height = height || 100
var color = color || 'red'
var url = url || 'https://www.xxx.com/'
...
}
定义默认参数(ES6)
var link = function(height = 100, color = 'red', url = 'http://xxx.com') {
...
}
No3.(模版表达式)
模版表达式(以前)
var name = 'tester name is ' + first + ' ' + last + '.'
var url = 'https://www.xxx.com/' + id
模板表达式(ES6)
var name = `tester name is ${first} ${last}`
var url = `https://www.xxx.com/${id}`
//反引号和${NAME}的使用,简约而不简单
No4.(多行字符串)
多行字符串(以前)
var roadPoem = 'The line is first step'
+ 'The line is first step'
+ 'The line is first step'
+ 'The line is first step'
+ 'The line is first step'
var fourAgreements = 'The line is first step.'
多行字符串(ES6)
var roadPoem = `The line is first step
The line is first step
The line is first step
The line is first step
The line is first step`
var fourAgreements = `The line is first step.`
No5.(拆包表达式)
拆包表达式(以前)
var data = $('body').data(), // 假设data中有mouse和house的值
house = data.house,
mouse = data.mouse
拆包表达式(ES6)
var { house, mouse} = $('body').data() // 我们会拿到house和mouse的值的
No6.(箭头函数)
箭头函数(以前)
var _this = this //我们需要指明作用域
$('.btn').click(function(event){
_this.sendData()
})
箭头函数(ES6)
$('.btn').click((event) =>{
this.sendData()
})
//使用了箭头函数以后,我们不再用that = this或者self = this或者_this = this或者.bind(this)这样的代码
我们再来看一组(加点料)
//老旧版本
var logUpperCase = function() {
var _this = this
this.string = this.string.toUpperCase()
return function () {
return console.log(_this.string)
}
}
logUpperCase.call({ string: 'es6 rocks' })()
//ES6版本
var logUpperCase = function() {
this.string = this.string.toUpperCase()
return () => console.log(this.string)
}
logUpperCase.call({ string: 'es6 rocks' })()
//注意,在ES6中你可以合理的把箭头函数和旧式 function 函数混用。当箭头函数所在语句只有一行时,它就会变成一个表达式,它会直接返回这个语句的值。但是如果你有多行语句,你就要明确的使用return。
最后我们看一看数组(0.0)
//这是我们以前的写法
var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
var messages = ids.map(function (value) {
return 'ID is ' + value // 显式返回
});
//这是ES6的写法
var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
var messages = ids.map(value => `ID is ${value}`) // 隐式返回
//在只有一个参数的函数签名中,括号是可有可无的,但是如果多于一个参数时就要加上。
var ids = ['5632953c4e345e145fdf2df8','563295464e345e145fdf2df9']
var messages = ids.map((value, index, list) => `ID of ${index} element is ${value} `) // 隐式返回
No7.(Promise)
Promise(以前)
setTimeout(function(){
console.log('Yay!')
}, 1000)
Promise(ES6)
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!')
})
No8.(类)
类(过往不究,我们直接看ES6如何创建一个类)
class baseModel {
constructor(options = {}, data = []) { // class constructor
this.name = 'Base'
this.url = 'http://azat.co/api'
this.data = data
this.options = options
}
getName() { // class method
console.log(`Class name: ${this.name}`)
}
}
//注意到我给options和data用了默认参数,而且方法名再也不用加上function或者:了。还有一个很大的区别,你不能像构造函数里面一样向this.Name指派值。怎么说呢,和函数有相同缩进的代码里,你不能向name赋值。如果有这个需要的话,在构造函数里面完成。
No9.(模块化)
模块化
module.exports = {
port: 3000,
getAccounts: function() {
...
}
}
在ES5的main.js中,用require(‘模块’)来导入:
var service = require('module.js')
console.log(service.port) // 3000
但是在ES6中,我们用export和import。比如这是ES6中的module.js文件:
export var port = 3000
export function getAccounts(url) {
...
}
在需要引入的main.js文件中,可以用import {名称} from ‘模块’语法:
import {port, getAccounts} from 'module'
console.log(port) // 3000
或者就直接在main.js中引入所有的变量:
import * as service from 'module'
console.log(service.port) // 3000
……
ES6标准中,包括但不仅限于本文中的内容,本文旨在交流学习,请不要用于商业用途,最后希望本文能够对你有帮助!