[英]calling a function vs returning the function call - difference?
If there a function, say foo
: 如果有函数,请说foo
:
function foo() {
console.log('bar');
}
then in JavaScript, Is there any difference between calling a function from another function, like this: 然后在JavaScript中,从另一个函数调用一个函数之间是否有任何区别,如下所示:
function baz() {
foo();
}
baz();
and returning the function call, like this: 并返回函数调用,如下所示:
function baz() {
return foo();
}
baz();
both approaches give the same output (string output: 'bar'). 两种方法都提供相同的输出(字符串输出:“ bar”)。
If you return, then the rest of the function won't execute … but in your example there is no more code after the return line, so it makes no difference. 如果返回,则该函数的其余部分将不会执行……但是在您的示例中,返回行后没有更多代码,因此没有区别。
If you don't explicitly return a value, then you return undefined
… but foo
returns undefined
anyway and you don't do anything with the return value of baz
so it makes no difference. 如果没有显式返回值,则返回undefined
…但是foo
无论如何都返回undefined
, 并且您对baz
的返回值不执行任何操作,因此没有区别。
There is no practical difference between your two examples. 您的两个示例之间没有实际区别。
You are not return any thing .you are just console.log('bar')
inside the foo
. 您什么也没返回,只是foo
内部的console.log('bar')
。 its just ah calling
not returning .see the original return call statement.Its give the undefined
value from your second one 它只是ah calling
而未返回。请参阅原始的return调用语句。它给出第二个undefined
值
Second one was wrong 第二个错了
function foo() { return 'bar'; //this is return the `bar` } function baz() { foo(); //its calling but not returning } console.log(baz());
So you need to return the function inside the another function call 因此,您需要在另一个函数调用中返回该函数
function foo() { return 'bar'; } function baz() { return foo(); //return is important to returning the value from the function } console.log(baz());
Strictly speaking, your second example is wrong in 2 ways: 1) you call return with the function that doesn't return anything 2) you doesn't check for return value, so what is the need to call it this way? 严格来说,您的第二个示例在2种方面是错误的:1)您使用不返回任何内容的函数调用return; 2)您不检查返回值,那么用这种方式调用它是什么呢?
But even if you would check, it will return undefined, so no use. 但是即使您进行检查,它也会返回未定义的内容,因此没有用。
The output is identical so there doesn't seem to be a reason to prefer one way of invoking the function over another. 输出是相同的,因此似乎没有理由更喜欢一种调用函数的方法。 After all they both return by default undefined. 毕竟,它们默认都返回undefined。 But, I think returning the result of the function can sometimes be useful even if the return result is undefined. 但是,我认为即使未定义返回结果,返回函数的结果有时也很有用。 By returning undefined it can be captured in an if-conditional which would allow other statements to execute, as follows: 通过返回undefined,可以在if条件中捕获它,该条件将允许其他语句执行,如下所示:
function foo() { console.log('bar'); } function baz() { foo(); } baz(); function baz2() { return foo(); } if ( baz2() == undefined) { // execute statements ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.