2014-01-24 64 views
0

我需要檢測兩個匿名函數是否相同。你可以比較JavaScript中的匿名函數嗎?

在控制檯中,爲什麼以下行返回false

(function() { alert("hello"); }) === (function() { alert("hello"); })

是否有一個比較操作或其他方法來確定,這些都是「功能」一樣嗎?

編輯:

人都在問的使用這一點。

它用於刪除以前被推入一個函數數組的函數。請參閱http://jsfiddle.net/w6s7J/進行簡化測試。

+2

'.toString()'在雙方,但它非常粗糙。 –

+1

爲什麼?這是否有真正的生活用途? – Dalorzo

+0

我99%肯定有一個更好的方法來做任何你試圖做 –

回答

1

有比較2個不同的匿名函數「功能」沒有真正的方法。

您可以使用您的示例代碼檢查它們是否是相同的對象。

var func = function() { 
    alert('hello'); 
}; 

alert(func === func); 

上面的方法是有效的,因爲您正在檢查兩個對象是否相同。

唯一的比較方法是將它們作爲字符串進行比較。

var func1 = function() { 
    alert("hello"); 
}; 

var func2 = function() { 
    alert('hello'); 
}; 

alert(func1.toString() === func2.toString()); 

糟糕!,它們在功能上是相同的,區別在於使用的引號,所以這返回false。

1
(function() { alert("hello"); }) === (function() { alert("hello"); }) 

返回 beacouse它是在JavaScript中不同的對象。

(function() { alert("hello"); }).toString() === (function() { alert("hello"); }).toString() 

返回真正,因爲它們是相同的字符串。

而且函數對象具有name財產返回函數的名稱(但not works in IE):

var a = function b() {} 
alert(a.name);//write b 
+0

但是'(function(){})。toString()===(function(){})。toSting()/ /虛因'因爲空間。 –