2014-03-26 42 views
0

我對JS 1.7的新yield特性產生一個值時有點困惑。何時在Javascript中執行yield語句?

當我寫我的功能是這樣的:

function helloWorld() { 
    console.log('hello'); 
    yield "world"; 
} 

var sayHello = helloWorld(); 

sayHello.next(); 

它返回:

>"world" 
>"hello" 

但是,當我寫我的功能是這樣的:

function helloWorld() { 
    console.log('hello'); 
    yield console.log("world"); 
} 

var sayHello = helloWorld(); 

sayHello.next(); 

它返回:

>"hello" 
>"world" 

正如我所料。

我很困惑,爲什麼在第一種情況下,「世界」會在「你好」之前返回,也許我不明白產量是如何工作的,任何人都可能知道詳細說明爲什麼產量會如此表現?

+2

請看這裏http://stackoverflow.com/questions/2282140/whats-the-yield-keyword-in-javascript可能會回答你的問題。 – Christos

+0

啊,我在開始玩產量表時玩過這個遊戲,這比較了收益率和回報率。但是如果我用返回來替換世界產量,它在返回「世界」之前仍然會記錄「你好」。我想知道爲什麼在下一次調用時,yield值在「world」之前返回,如果它是原始的?我非常熟悉生成器並在python中生成,但這在新的JS實現中似乎很奇怪。 – Derek

回答

0

對不起,這似乎是一個錯誤。

我嘗試使用使用Firefox控制檯產量和它輸出的這一點,但之後我居然構建一個實際的文件並運行它雖然Firefox瀏覽器的表現如預期

如果有人好奇

<html> 
<head> 
</head> 
<body> 
<script type="application/javascript;version=1.7" > 
function helloWorld() { 
    console.log("hello"); 
    yield "world"; 
    yield "END"; 
} 

var sayHello = helloWorld(); 

console.log(sayHello.next()); 

function helloWorld1() { 
    console.log('hello'); 
    yield console.log("world"); 
    yield "END2"; 
} 

var sayHello1 = helloWorld1(); 

sayHello1.next(); 
console.log(sayHello.next()); 
console.log(sayHello1.next()); 
</script> 
</body> 
</html> 

輸出:

「你好」 「世界」 「你好」 「世界」 「END」 「END2」