2012-02-24 107 views
6

假设你有没有返回值有和没有返回语句的函数有区别吗?

function a() { 
    // do some interesting things 
} 

function b() { 
    // do the same interesting things 
    return; 
} 

功能b显然更为冗长,但有它们之间的任何功能上的区别2层相同的功能呢?

+2

一个很好的答案,这应包括一个链接到ECMA的相关部分规范。 – georg 2012-02-24 18:04:57

+2

return;基本上就是在这里终止函数所以如果你把它作为你的函数的最后一点,它不会做任何有用的事情。 – gintas 2012-02-24 18:09:06

+1

12.9在spec中,对于那些感兴趣的人。 – davin 2012-02-24 18:50:26

回答

10

没有真正的区别;两者都将返回undefined

没有返回语句的函数将返回undefined,因为将使用空的return语句。


为了证实自己这一点,你可以运行这段代码 - FIDDLE

​function a() { 
} 

function b() { 
    return; 
} 

var aResult = a(); 
var bResult = b(); 

alert(aResult === bResult); //alerts true 
1

一般要返回的值。因此,例如,

function b() { 
    return 'hello'; 
} 

a = b(); 

console.log(a); 

将输出“hello”到您的控制台。

3

亚当是正确的;这两个函数都会返回未定义的值,如果您不关心返回值(或者希望该值未定义),那么两种方法都绝对没问题。但是,在更复杂的程序中显式返回函数通常更好,特别是因为Javascript程序通常具有复杂的回调机制。例如,在这段代码(只是多一点比你复杂的)我相信return语句确实有助于澄清代码:

function someAsyncFunction(someVar, callback) { 
    // do something, and then... 
    callback(someVar); 
    // will return undefined 
    return; 
} 

function c(){ 
    var someState = null; 
    if (some condition) { 
     return someAsyncFunction(some variable, function() { 
      return "from the callback but not the function"; 
     }); 
     // we've passed the thread of execution to someAsyncFunction 
     // and explicitly returned from function c. If this line 
     // contained code, it would not be executed. 
    } else if (some other condition) { 
     someState = "some other condition satisfied"; 
    } else { 
     someState = "no condition satisfied"; 
    } 
    // Note that if you didn't return explicitly after calling 
    // someAsyncFunction you would end up calling doSomethingWith(null) 
    // here. There are obviously ways you could avoid this problem by 
    // structuring your code differently, but explicit returns really help 
    // avoid silly mistakes like this which can creep into complex programs. 
    doSomethingWith(someState); 
    return; 
} 

// Note that we don't care about the return value. 
c(); 
+3

完全主观,但我完全不同意。我认为这不会让代码更容易阅读。相反,这是不必要的,所以它只会造成混乱。我的2c。我想每一个都是属于他自己的。 – davin 2012-02-24 18:44:26