学习笔记-2018年10月第五周 - ES6新特性

ES6 = ECMASCript2015

模板字符串

不使用ES6的情况

1
var name = 'My name is ' + firstName + ' ' + lastName

使用ES6

1
var name = 'My name is ${firstName} ${lastName}'

多行字符串

不使用ES6(使用”\n\t”拼接多行字符串)

1
2
3
var greeting = 'Hi how are you I am Aaron,\n\t'
+ 'I am based in Auckland.\n\t'
+ 'Have a nice day'

使用ES6(将多行字符串放在反引号之间)

1
2
3
var greeting = `Hi how are you I am Aaron,
I am based in Auckland
Have a nice day`

对象属性简写

不使用ES6(对象中必须包含属性和值)

1
2
3
4
5
6
7
8
9
var firstName = 'Aaron'
var lastName = function(){
//....
}

var person = {
firstName: firstName,
lastName: lastName
}

使用ES6

1
2
3
4
5
6
var firstName = 'Aaron'
var lastName = function(){
//...
}

var person = { firstName, lastName };

箭头函数

基本语法:

1
let func = value => value;

相当于:

1
2
3
let function = function(value) {
return value
}

不使用ES6(普通函数体内的this,只想调用时所在的对象)

1
2
3
4
5
6
7
function test() {
console.log(this.id)
}

var id = 1;
test(); //输出1
test({id:2}); 输出2

使用ES6(箭头函数体内的this,就是定义所在的对象,而不是调用时所在的对象)

1
2
3
4
5
6
7
var test = () => {
console.log(this.id)
}

var id = 1
test(); //输出1
test.call({id:2}); 输出1

ES6有两种格式,一种是当仅有一个表达式时

1
var getAmount = x => x * x;

还有一种是包含多种语句的,那就必须要有{ }和return

1
2
3
4
5
6
7
var getAmount = x => {
if (x > 0) {
return x * x
} else {
return -x * x
}
}

使用箭头函数比普通函数少了些动词,比如function或者return

Promise

不使用ES6
待完善

Let & Const

使用var(var定义的变量为函数级作用于)

1
2
3
4
{
var a = 10;
}
console.log(a); //输出10

使用let(块级作用于)

1
2
3
4
{
var a = 10;
}
console.log(a); //ReferenceError: a is not defined

class

不使用ES6(使用函数构造创建对象)

1
2
3
4
5
6
7
8
9
function amount(x, y) {
this.x = x
this.y = y
this.add = function() {
return this.x + this.y
}
}
var p = new amount(1, 2)
console.log(p.add()) //输出3

使用ES6(用class定义,更规范,并且可继承)

1
2
3
4
5
6
7
8
9
10
11
12
class amount {
constructor(x, y)
{
this.x = x
this.y = y
}
this.add = function() {
return this.x + this.y
}
}
var p = new amount(1, 2)
console.log(p.add()) //输出 3

模块化

js一直没有官方的模块化解决方案,ES6指定了模块化功能
ES6使用export和import关键词来实现模块化

1
2
3
4
export firstName = 'Aaron'
export function getLastName() {
//...
}

并且在另外一个文件中用import导入,可以指定需要导入的变量

1
2
import {port, getLastName} from 'module'
console.log(firstName) //输出Aaron

也可以将变量一次性全部导入

1
2
import * as person from 'module'
console.log(person.firstName); //输出Aaron