Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/378.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何比较javascript中的两个函数_Javascript_Function - Fatal编程技术网

如何比较javascript中的两个函数

如何比较javascript中的两个函数,javascript,function,Javascript,Function,如何比较javascript中的两个函数? 我不是说内部参考。说 var a = function(){return 1;}; var b = function(){return 1;}; 是否可以比较a和b?您可以比较可能包含函数引用的两个变量,以查看它们是否引用完全相同的函数,但您无法真正比较两个单独的函数,以查看它们是否执行相同的操作 var a = b = function( c ){ return c; }; //here, you can use a === b because t

如何比较javascript中的两个函数? 我不是说内部参考。说

var a = function(){return 1;};
var b = function(){return 1;};

是否可以比较
a
b

您可以比较可能包含函数引用的两个变量,以查看它们是否引用完全相同的函数,但您无法真正比较两个单独的函数,以查看它们是否执行相同的操作

var a = b = function( c ){ return c; };
//here, you can use a === b because they're pointing to the same memory and they're the same type

var a = function( c ){ return c; },
    b = function( c ){ return c; };
//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),

''+a == ''+b.

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

a.toString( ) == b.toString( )  
例如,您可以执行以下操作:

function foo() {
    return 1;
}

var a = foo;
var b = foo;

a == b;   // true
但是,您无法可靠地做到这一点:

function foo1() {
    return 1;
}

function foo2() {
    return 1;
}

var a = foo1;
var b = foo2;

a == b;   // false
你可以在这里看到第二个:


在某些情况下,您可以在函数上使用
.toString()
运算符,但这是将函数的文字字符串转换与另一个函数的文字字符串转换进行比较,即使有一点点与函数实际生成的内容无关,也不会起作用。我想不出在什么情况下,我会建议将其作为一种可靠的比较机制。如果你真的想这样做,我会问为什么?您真正想要完成的是什么,并试图找到一种更有效的解决问题的方法。

闭包意味着您需要非常小心地说出“比较”的意思。例如:

function closure( v ) { return function(){return v} };
a = closure('a'); b = closure('b');
[a(), b()]; // ["a", "b"]

// Now, are a and b the same function?
// In one sense they're the same:
a.toString() === b.toString(); // true
// In another sense they're different:
a() === b(); // false
能够到达函数外部意味着在一般意义上,比较函数是不可能的

然而,从实际意义上讲,使用诸如Esprima或Acorn之类的Javascript解析库可以有很长的路要走。通过这些,您可以构建一个“抽象语法树”(AST),它是程序的JSON描述。例如,ast your
return 1
函数如下所示

ast = acorn.parse('return 1', {allowReturnOutsideFunction:true});
console.log( JSON.stringify(ast), null, 2)
{
  "body": [
    {
      "argument": {
        "value": 1,              // <- the 1 in 'return 1'
        "raw": "1",
        "type": "Literal"
      },
      "type": "ReturnStatement" // <- the 'return' in 'return 1'
    }
  ],
  "type": "Program"
}
// Elided for clarity - you don't care about source positions
ast=acorn.parse('return1',{allowerturnoutsidefunction:true});
log(JSON.stringify(ast),null,2)
{
“正文”:[
{
“论点”:{

“value”:1,//将函数转换为字符串,然后在比较之前替换换行符和空格:

设a=函数(){
返回1
};
设b=函数(){
返回1
};
a=a.toString().replace(/\n/g')。replace(/\s{2}/g');
b=b.toString().replace(/\n/g')。replace(/\s{2}/g');
console.log(a);//'函数(){return 1}'
console.log(b);//'函数(){return 1}'
console.log(a==b);//true
b=函数(){
返回2
};
b=b.toString().replace(/\n/g')。replace(/\s{2}/g');
console.log(b);//'函数(){return 2}'
console.log(a==b);//false
b=()=>3;
b=b.toString().replace(/\n/g')。replace(/\s{2}/g');
console.log(b);/“()=>3”
console.log(a==b);//函数上的false
toString()返回准确的声明。您可以修改jfriend00的代码来测试它

这意味着您可以测试您的函数是否完全相同,包括您在其中添加了哪些空格和换行符

但首先你必须消除他们名字上的差异

function foo1() {
    return 1;
}

function foo2() {
    return 1;
}

//Get a string of the function declaration exactly as it was written.
var a = foo1.toString();
var b = foo2.toString();

//Cut out everything before the curly brace.
a = a.substring(a.indexOf("{"));
b = b.substring(b.indexOf("{"));

//a and b are now this string:
//"{
//    return 1;
//}"
alert(a == b); //true.
正如其他人所说,这是不可靠的,因为一个空格的差异使比较是错误的


但是,如果你把它作为一种保护措施(“自从我创建它以来,有人改变了我的函数吗?”)你可能真的需要这种严格的比较。

JavaScript甚至不会解析语法错误……但是,“比较”是什么意思?各种浏览器都支持“toString”在函数对象上使用不同的方法,因此在您的情况下可能会起作用(但在本例中不起作用,因为它不会解析,所以没有为
a
b
)分配任何内容)。我还认为有一些库可以“反映”JavaScript[在脚本块中]。由于JS中的所有内容都是一个对象-您可能会尝试找到类似smth的对象比较()。请注意,这适用于匿名函数(这是OP要求的),如果您有var a=function a(){…和var b=function b(){…(许多人都这样做,因为这样您可以在堆栈中获得更有意义的消息)那么就没有办法知道,对于具有相同代码的两个不同函数(可能发生在具有两个类方法的实词中),此方法也将计算为
true
。请注意,对于具有相同语法树但具有不同间距的函数,此方法将失败。如果像“function a(){return 1;}这样声明函数,它不起作用吗“?@TarekSalahuddinMahmud您可以再试一次。我只是再检查一次。它正在工作。
let
并不总是比
var
快。它们只是对变量的作用域不同,但通常效率相同。
const
肯定更快,因为它允许JIST优化。