http://es6.ruanyifeng.com/#docs/class
1.let
let
命令所在的代碼塊內(nèi)有效
{ let a = 10; var b = 1;}
a // ReferenceError:
a is not defined.b // 1
for循環(huán)的計(jì)數(shù)器,就很合適使用let命令。
不存在變量提升
var tmp = 123;
if (true) {
tmp = 'abc';
// ReferenceError
let tmp;
}
暫時(shí)性死區(qū)的本質(zhì)就是,只要一進(jìn)入當(dāng)前作用域,所要使用的變量就已經(jīng)存在了,但是不可獲取,只有等到聲明變量的那一行代碼出現(xiàn),才可以獲取和使用該變量。
2.const
const的作用域與let命令相同:只在聲明所在的塊級(jí)作用域內(nèi)有效。
var a = 1;// 如果在Node的REPL環(huán)境,可以寫成
global.a// 或者采用通用方法,寫成
this.awindow.a // 1
let b = 1;
window.b // undefined
3.類
class Logger {
constructor() {
//this.printName = this.printName.bind(this);
}
//可以有默認(rèn)值
printName(name = 'there') {
this.print(`Hello ${name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;//取出屬性
printName(); // TypeError: Cannot read property 'print' of undefined
2.Class的Generator方法
如果某個(gè)方法之前加上星號(hào)(*),就表示該方法是一個(gè)Generator函數(shù)。
class Foo {
constructor(...args) {
this.args = args;
}
* [Symbol.iterator]() {
for (let arg of this.args) {
yield arg;
}
}
}
for (let x of new Foo('hello', 'world')) {
console.log(x);
}
// hello
// world
4.Class的靜態(tài)方法
class Foo {
static classMethod() {
return 'hello';
}
}
class Bar extends Foo {
static classMethod() {
return super.classMethod() + ', too';
}
}
Bar.classMethod();
5.Class的靜態(tài)屬性和實(shí)例屬性
因?yàn)镋S6明確規(guī)定,Class內(nèi)部只有靜態(tài)方法,沒(méi)有靜態(tài)屬性。
靜態(tài)屬性指的是Class本身的屬性,即Class.propname
,而不是定義在實(shí)例對(duì)象(this)上的屬性。
class Foo {}
Foo.prop = 1;
Foo.prop // 1
Class屬性
class ReactCounter extends React.Component {
state = {
count: 0
};
}
為了可讀性可以直接列出來(lái)
class ReactCounter extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
state;
//static myStaticProp = 42;靜態(tài)的
}
5.多個(gè)接口實(shí)現(xiàn)
function mix(...mixins) {
class Mix {}
for (let mixin of mixins) {
copyProperties(Mix, mixin);
copyProperties(Mix.prototype, mixin.prototype);
}
return Mix;
}
function copyProperties(target, source) {
for (let key of Reflect.ownKeys(source)) {
if ( key !== "constructor"
&& key !== "prototype"
&& key !== "name"
) {
let desc = Object.getOwnPropertyDescriptor(source, key);
Object.defineProperty(target, key, desc);
}
}
}
```
上面代碼的mix函數(shù),可以將多個(gè)對(duì)象合成為一個(gè)類。使用的時(shí)候,只要繼承這個(gè)類即可。
```
class DistributedEdit extends mix(Loggable, Serializable) { // ...}
```
***
####1.對(duì)象轉(zhuǎn)數(shù)組
```
let arrayLike = {
'0': 'a',
'1': 'b',
'2': 'c',
length: 3
};
// ES5的寫法
var arr1 = [].slice.call(arrayLike); // ['a', 'b', 'c']
// ES6的寫法
let arr2 = Array.from(arrayLike); // ['a', 'b', 'c']
```