mirror of
https://github.com/ruanyf/es6tutorial.git
synced 2025-05-24 18:32:22 +00:00
edit generator/yield*
This commit is contained in:
parent
2b10934b80
commit
cf0dc095fc
@ -34,7 +34,7 @@ class之间可以通过extends关键字,实现继承。
|
|||||||
class ColorPoint extends Point {
|
class ColorPoint extends Point {
|
||||||
|
|
||||||
constructor(x, y, color) {
|
constructor(x, y, color) {
|
||||||
super(x, y); // same as super.constructor(x, y)
|
super(x, y); // 等同于super.constructor(x, y)
|
||||||
this.color = color;
|
this.color = color;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -46,7 +46,7 @@ class ColorPoint extends Point {
|
|||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
上面代码定义了一个ColorPoint类,该类通过extends关键字,继承了Point类的所有属性和方法。在constructor方法内,super就指代父类Point。
|
上面代码定义了一个ColorPoint类,该类通过extends关键字,继承了Point类的所有属性和方法。在constructor方法内,super就指代父类Point;在toString方法内,`super()`表示对父类求值,由于此处需要字符串,所以会自动调用父类的toString方法。
|
||||||
|
|
||||||
## Module的基本用法
|
## Module的基本用法
|
||||||
|
|
||||||
|
@ -178,3 +178,47 @@ for(let value of delegatingIterator) {
|
|||||||
// "Ok, bye."
|
// "Ok, bye."
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|
||||||
|
上面代码中,delegatingIterator是代理者,delegatedIterator是被代理者。由于`yield* delegatedIterator`语句得到的值,是一个遍历器,所以要用星号表示。
|
||||||
|
|
||||||
|
下面是一个稍微复杂的例子,使用yield*语句遍历二叉树。
|
||||||
|
|
||||||
|
```javascript
|
||||||
|
|
||||||
|
// 下面是二叉树的构造函数,
|
||||||
|
// 三个参数分别是左树、当前节点和右树
|
||||||
|
function Tree(left, label, right) {
|
||||||
|
this.left = left;
|
||||||
|
this.label = label;
|
||||||
|
this.right = right;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 下面是中序(inorder)遍历函数。
|
||||||
|
// 由于返回的是一个遍历器,所以要用generator函数。
|
||||||
|
// 函数体内采用递归算法,所以左树和右树要用yield*遍历
|
||||||
|
function* inorder(t) {
|
||||||
|
if (t) {
|
||||||
|
yield* inorder(t.left);
|
||||||
|
yield t.label;
|
||||||
|
yield* inorder(t.right);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 下面生成二叉树
|
||||||
|
function make(array) {
|
||||||
|
// 判断是否为叶节点
|
||||||
|
if (array.length == 1) return new Tree(null, array[0], null);
|
||||||
|
return new Tree(make(array[0]), array[1], make(array[2]));
|
||||||
|
}
|
||||||
|
let tree = make([[['a'], 'b', ['c']], 'd', [['e'], 'f', ['g']]]);
|
||||||
|
|
||||||
|
// 遍历二叉树
|
||||||
|
var result = [];
|
||||||
|
for (let node of inorder(tree)) {
|
||||||
|
result.push(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
// ['a', 'b', 'c', 'd', 'e', 'f', 'g']
|
||||||
|
|
||||||
|
```
|
||||||
|
@ -1,5 +1,7 @@
|
|||||||
# 参考链接
|
# 参考链接
|
||||||
|
|
||||||
|
## 官方文件
|
||||||
|
|
||||||
- [ECMAScript 6 Language Specification](http://people.mozilla.org/~jorendorff/es6-draft.html): 语言规格草案
|
- [ECMAScript 6 Language Specification](http://people.mozilla.org/~jorendorff/es6-draft.html): 语言规格草案
|
||||||
- [harmony:proposals](http://wiki.ecmascript.org/doku.php?id=harmony:proposals): ES6的各种提案
|
- [harmony:proposals](http://wiki.ecmascript.org/doku.php?id=harmony:proposals): ES6的各种提案
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user