1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-24 10:22:23 +00:00

edit generator/yield*

This commit is contained in:
ruanyf 2014-05-03 23:35:05 +08:00
parent 2b10934b80
commit cf0dc095fc
3 changed files with 48 additions and 2 deletions

View File

@ -34,7 +34,7 @@ class之间可以通过extends关键字实现继承。
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y); // same as super.constructor(x, y)
super(x, y); // 等同于super.constructor(x, y)
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的基本用法

View File

@ -178,3 +178,47 @@ for(let value of delegatingIterator) {
// "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']
```

View File

@ -1,5 +1,7 @@
# 参考链接
## 官方文件
- [ECMAScript 6 Language Specification](http://people.mozilla.org/~jorendorff/es6-draft.html): 语言规格草案
- [harmony:proposals](http://wiki.ecmascript.org/doku.php?id=harmony:proposals): ES6的各种提案