简体   繁体   中英

Javascript: Checking equality of the functions themselves, not return values

I want to pass a function into another as a property. I then want to test whether that function is equal to a particular function:

function f(func) {
    if (func === testFunc) {
        console.log("They're the same!")
    }
}

function testFunc(x) {
   return x+1
}

f(testFunc)

The above works as expected. The conditional in the top function passes and the line is outputted to the console. However, if I pass the function with a property of its own, it is found not to be equal:

f(testFunc(2))

I assume this is because the return value is different. So how do I test whether the actual functions are the same, not their returning values? Is there a way?

If you want to check, if 2 object's content are the same, then you need to use the uneval function. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/uneval

Keep in mind this is worse than eval, so try to avoid it if possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM