2012-05-24 62 views
1

在JavaScript中,假設您有:有沒有辦法查看一個(匿名)函數?

function doSomething(callback) { 
    if (callback instanceof Function) callback(); 
} 

doSomething(function() { 
    alert('hello world'); 
}); 

有沒有一種方法來檢查裏面是什麼「回調」(喜歡,事實證明alert()叫)從doSomething()?喜歡的東西:

function doSomething(callback) { 
    alert(callback.innards().indexOf('alert(')); 
} 

我只是好奇

+5

你爲什麼想要做這樣的事情? – asawyer

+1

關於typeof與instanceof的很好的討論在這裏:http://stackoverflow.com/questions/899574/which-is-best-to-use-typeof-or-instanceof – ScottE

回答

2

Function.prototype.toString()給出了一個implementation-dependent representation of the function。然而,內置函數將返回如下內容:

function Array() { 
    /* [native code] */ 
} 

和主機方法可以返回任何內容,甚至會拋出錯誤。所以嚴格的答案是肯定的,也許。但從實際意義上講,這並不可靠。

1

有些瀏覽器支持toString()上的功能。

function doSomething(callback) { 
    console.log(callback.toString().indexOf('alert(')) 
    if (callback instanceof Function) callback(); 
} 
+0

'有些瀏覽器'?它在[ECMA-262](http://es5.github.com/#x15.3.4.2)中,所以我希望所有瀏覽器都支持它。你知道任何沒有的瀏覽器嗎? – RobG

+0

[這不是那麼簡單。](http://jsfiddle.net/YxRbn/) – Saxoier

+0

@Saxoier duh,這是一個文本匹配。這不會是準確的。你錯過了'var foo =「alert()」;' – epascarello

0

你應該能夠說:

alert(callback.toString().indexOf('alert(')); 

然而,這將不是一個函數alert(的開始區分,功能myspecialalert(的開始,和文本"alert("如果碰巧在字符串文字中 - 所以你可能需要做一些解析。

不知道這是如何跨瀏覽器,但在Firefox中至少返回.toString()函數的全部文本,包括單詞「功能」和參數列表。

0
callback.toString().indexOf('alert('); 

或者做一個正則表達式匹配,如:

/alert *\(/.test(callback.toString()); 
相關問題