开发者

how compare two static function are equal or not in javascript [duplicate]

This question already has answers here: 开发者_运维问答 how do I compare 2 functions in javascript (6 answers) Closed 6 years ago.

how to compare two static functions in javascript equal or not equal?


String(f1) === String(f2)


var f1 = f2 = function( a ){ return a; };

here, you can use f1 === f2 because they're pointing to the same memory and they're the same type

var f1 = function( a ){ return a; },
    f2 = function( a ){ return a; };

here you can use that byte-saver Andy E used (which is implicitly converting the function to it's body's text as a String),

''+f1 == ''+f2.

this is the gist of what is happening behind the scences:

f1.toString( ) == f2.toString( )  

Edit: Looking back on this post over a year after, I agree with @kangax - you should probably never do this.


Whenever I need to compare functions I make sure there is no scope ambiguity and use the same function object.

Say I have some a pair of library functions that take a callback as one of the parameters. For the sake of this example create1minuteCallback function will set a 1 minute timer and call the callback on each tick. kill1minuteCallback will turn off the callback and you must pass the same callback function as you did for create1minuteCallback.

function create1minuteCallback(callback){
//implementation
}

function kill1minuteCallback(callback){
//implementation
}

Quite clearly this will not work as the function we are passing is different on the second line:

create1minuteCallback(function(){alert("1 minute callback is called");});
kill1minuteCallback(function(){alert("1 minute callback is called");});

I normally do this:

function callbackFunc(){alert("1 minute callback is called");}

create1minuteCallback(callbackFunc);
kill1minuteCallback(callbackFunc);


Well, as simply as that - if you are going to compare functions, you do it for a reason I assume. What is your reason? My reason was to not run a certain function twice. I did it this way (just snippet code to get the idea)

   var x = function(){
    console.error("i am a functionX");
  }
   var y = function(){
        console.error("i am a functionX");



  }

    var z = function(){
       console.error("i am a functionZ");



  }
       var x2= x;

   var obj = new Object();
    obj[x] = "";
    obj[x2] = "";
    obj[y] = "";
    obj[z] = "";
    obj.abc = "xaxa";
                for (prop in obj) {
                    if (obj.hasOwnProperty(prop)) {
                      console.error(obj[prop] + " hello " + prop);
                    }
            }

Function x and y are the same, even though they have different whitespaces. x and y are not the same as z, since z has a different console.error. Btw open your firebug console to see it in the jsbin example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜