I have spent a lot of time with yield recently, and bobince isn't completely wrong, but Chrome 31 does not interpret JavaScript version to 1.7 blocks, even with the Experimental JavaScript flag turned on (chrome://flags/#enable-javascript-harmony). Due to implementation differences between Chrome 31 and Firefox, Tymon Sturgeon's method is unable to detect yield in Chrome 31 with Experimental JS on, although it is very close. With a few modifications, it can detect the existence of yield for both Firefox and Chrome 31 with Experimental JS on.
First I'll quickly cover the yield differences (writing it the long way for clarity):
In Firefox:
var fooGen = function(){ yield 1; yield 2; };
var iterator = fooGen();
console.log(iterator.next()); // prints 1
console.log(iterator.next()); // prints 2
In Chrome 31 with Experimental JavaScript enabled:
// Note the *
var fooGen = function*(){ yield 1; yield 2; };
var iterator = fooGen();
console.log(iterator.next().value); // prints 1
console.log(iterator.next().value); // prints 2
.value is required in Chrome because it yields an object, but more importantly, the generator requires a "*" in the function definition. Also, I could not find a way to create a generator from the capital "F" Function: new Function('', '{yield 5;}'); in Chrome. If you know how, leave a comment below.
To properly detect yield in Firefox and Chrome, I have used a bit of code with some back and forth:
<script type="application/javascript">
var can_yield = (function(){
try {
// Assuming Chrome's generator syntax
var funcUsingYield = new Function('', '{ var interp = function* generator(){ yield true; }}');
return true;
} catch(e) {
return false;
}
})();
</script>
<script type="application/javascript;version=1.7">
// Redefine the `can_yield` function inside a JS1.7 block. Probably safe to simply return true
can_yield = (function(){
try {
return eval("!!Function('yield true;')().next()");
}
catch(e) {
return false;
}
})();
</script>
<script type="application/javascript">
if(!can_yield)
{
alert("Can't Yield!");
}
</script>
Tested in:
- Firefox 25:
yield works
- Chrome 31 with Experimental JS On:
yield works
- Chrome 31 with Experimental JS Off:
yield does not work
- and IE10:
yield does not work