2016-04-27 96 views
1

此代碼迭代通過發電機在ES6

let func = function *(){ 
    for (let i = 1; i < 5; i++) { 
     yield i; 
    } 
} 
let s = func().next(); 
console.log(s); 
let s2 = func().next(); 
console.log(s2); 

返回

Object {value: 1, done: false} 
Object {value: 1, done: false} 

所以基本上FUNC產量第一值的所有時間。

但是,當我改變

let f = func(); 
let s = f.next(); 
console.log(s); 
let s2 = f.next(); 
console.log(s2); 

它按預期工作。 爲什麼將func分配給變量會產生這樣的差異?

+0

因爲' func()!== func()'? – Bergi

+0

如果它的行爲不同,那麼每個生成器函數只能使用*一次* ... –

回答

3

在您的第一個代碼中,您總是創建一個新的生成器實例。我已經分配的情況下分離變量這更清楚地說明:

// first generator instance 
let g = func(); 
// first call to next on the first instance 
let s = g.next(); 
console.log(s); 
// second generator instance 
let g2 = func(); 
// first call to next on the second instance 
let s2 = g2.next(); 
console.log(s2); 

而在你的第二個片段,你不斷迭代相同發生器(賦值給變量f):

let f = func(); 
// first call to next 
let s = f.next(); 
console.log(s); 
// second call to next 
let s2 = f.next(); 
console.log(s2);