es6基础(3)

es6标准入门

async

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
(async(){
function promisefn(url){
return Promise(function(resolve,reject){
$.ajax({
url: url,
success:function(){
resolve(response)
},
error:function(){
reject("error")
}
})
})
}
const a1 = await promisefn("http://www.xxx.com/a")
const a2 = await promisefn("http://www.xxx.com/b")
})()

Decorator(修饰器)

core-decorators.js

  1. @autobind

autobind装饰器使得方法中的this对象,绑定原始对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import { autobind } from 'core-decorators';

class Person {
@autobind
getPerson() {
return this;
}
}

let person = new Person();
let getPerson = person.getPerson;

getPerson() === person;
// true
  1. @readonly

readonly装饰器使得属性或方法不可写。

1
2
3
4
5
6
7
8
9
10
import { readonly } from 'core-decorators';

class Meal {
@readonly
entree = 'steak';
}

var dinner = new Meal();
dinner.entree = 'salmon';
// Cannot assign to read only property 'entree' of [object Object]
  1. @override

override装饰器检查子类的方法,是否正确覆盖了父类的同名方法,如果不正确会报错。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import { override } from 'core-decorators';

class Parent {
speak(first, second) {}
}

class Child extends Parent {
@override
speak() {}
// SyntaxError: Child#speak() does not properly override Parent#speak(first, second)
}

// or

class Child extends Parent {
@override
speaks() {}
// SyntaxError: No descriptor matching Child#speaks() was found on the prototype chain.
//
// Did you mean "speak"?
}

symbol

  1. 消除魔法字符串

魔术字符串指的是,在代码之中多次出现、与代码形成强耦合的某一个具体的字符串或者数值。风格良好的代码,应该尽量消除魔术字符串,改由含义清晰的变量代替。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function getArea(shape, options) {
let area = 0;

switch (shape) {
case 'Triangle': // 魔术字符串
area = .5 * options.width * options.height;
break;
/* ... more code ... */
}

return area;
}

getArea('Triangle', { width: 100, height: 100 }); // 魔术字符串

上面代码中,字符串Triangle就是一个魔术字符串。它多次出现,与代码形成“强耦合”,不利于将来的修改和维护。
常用的消除魔术字符串的方法,就是把它写成一个变量。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const shapeType = {
triangle: 'Triangle'
};

function getArea(shape, options) {
let area = 0;
switch (shape) {
case shapeType.triangle:
area = .5 * options.width * options.height;
break;
}
return area;
}

getArea(shapeType.triangle, { width: 100, height: 100 });

上面代码中,我们把Triangle写成shapeType对象的triangle属性,这样就消除了强耦合。

如果仔细分析,可以发现shapeType.triangle等于哪个值并不重要,只要确保不会跟其他shapeType属性的值冲突即可。因此,这里就很适合改用 Symbol 值。

1
2
3
const shapeType = {
triangle: Symbol()
};

上面代码中,除了将shapeType.triangle的值设为一个 Symbol,其他地方都不用修改。

map

把 键值对 obj 都换成 map