当前位置: 动力学知识库 > 问答 > 编程问答 >

Can you compare anonymous functions in javascript?

问题描述:

This question already has an answer here:

  • how do I compare 2 functions in javascript

    4 answers

网友答案:

There is no real way to compare 2 different anonymous functions for 'functionality'.

You can check if they are the same object by using your example code.

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

alert(func === func);

The above will work, as you are checking to see that both objects are the same.

The only other method for comparing is to compare them as a string.

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

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

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

Oops!, they are functionally the same, the difference is the quotes used, So this returns false.

网友答案:
(function() { alert("hello"); }) === (function() { alert("hello"); })

Return false beacouse its are the different objects in javascript.

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

Return true because they are the same strings.

Also function objects has name property which return the name of the function(but it not works in IE):

var  a = function b() {}
alert(a.name);//write b
分享给朋友:
您可能感兴趣的文章:
随机阅读: