2014-03-13 43 views

回答

2

我不喜歡這種方式:

var 
    // pull out regex for speed 
    genRegex = /^function[\s]*\*/, 

    detectGenerator = function(mth){ 
    return (typeof mth == 'function') && 
    genRegex.test(mth.toString()); 
    }; 


function * foo(){}; 
function *bar(){}; 
function* baz(){}; 
function*qux(){}; 
function non(){}; 

console.log(detectGenerator(function(){}), detectGenerator(function(){})) // false, false 
console.log(detectGenerator(function *(){}), detectGenerator(function* (){})) // true, true 
console.log(detectGenerator(function *(){}), detectGenerator(function*(){})) // true, true 
console.log(detectGenerator(foo), detectGenerator(bar)) // true, true 
console.log(detectGenerator(baz), detectGenerator(qux)) // true, true 
console.log(detectGenerator(non)) // false 

,但它的工作原理。

如果您有更好的選擇,請回復。

+0

你必須調整你的正則表達式到指定的函數。 –

+0

應該這樣做 – Funkodebat