Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test for equality of functions in Javascript [duplicate]

How would I get a positive test for bar and foo's equality?

 foo = function() {     a = 1;  };    bar = function() {     a = 1;  };    if (foo === bar) alert('baz');  if (foo == bar) alert('qux'); 

Both the above conditionals are false.

Updated - As requested the reason I need to test for function equality

I am building a Publish/Subscribe framework and need to pass the callback inorder to unsubscribe to a topic.

Please see the fiddle: http://jsfiddle.net/jamiefearon/hecMS/47/

like image 834
Jamie Fearon Avatar asked Aug 31 '12 13:08

Jamie Fearon


People also ask

What is == and === in JavaScript?

== is used for comparison between two variables irrespective of the datatype of variable. === is used for comparision between two variables but this will check strict type, which means it will check datatype and compare two values.

How do you find the equality of a function?

Two functions are equal if they have the same domain and codomain and their values are the same for all elements of the domain.

Can we compare two functions in JavaScript?

JavaScript provides 3 ways to compare values: The strict equality operator === The loose equality operator == Object.is() function.

What does === mean in JavaScript?

The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.


1 Answers

You could check whether the content of two functions is exactly the same by comparing the result of calling toString on them

 var foo = function() {     a = 1;  };    var bar = function() {     a = 1;  };   alert(foo.toString() == bar.toString());​ 

That will, however, fail if there is but one character that is different. Checking to see if two functions do the same thing, on the other hand, is pretty much impossible.

like image 117
Alex Turpin Avatar answered Sep 28 '22 08:09

Alex Turpin