[英]The difference between returning a function vs statement inside a function
I'm reading Eloquent JS and the example of closures has a code of block that returns a function returning a value. 我正在阅读Eloquent JS,闭包的例子有一个块代码,它返回一个返回值的函数。 What is the difference between that and returning the value right away.
它之间的区别是什么,立即返回值。
// returning value
function wrapValue(n) {
let local = n;
return local;
}
let wrap1 = wrapValue(1);
let wrap2 = wrapValue(2);
console.log(wrap1);
// → 1
console.log(wrap2);
// → 2
// returning a value with a function
function wrapValue2(n) {
let local = n;
return () => local;
}
let wrap3 = wrapValue2(3);
let wrap4 = wrapValue2(4);
console.log(wrap3());
// → 3
console.log(wrap4());
// → 4
For the purpose of just logging the same value without doing anything else to it, there is absolutely no difference whatsoever. 为了只记录相同的值而不做任何其他事情,绝对没有任何区别。
But there are scenarios where you have to do some other operation later on upon returning the value like so 但有些情况下,您必须在返回值后再执行其他操作
function doubleTheValue(n){ const val = n * 2; return () => val * 2; } const doubleValueAgain = doubleTheValue(2); console.log(doubleValueAgain());
So to answer your question, if you try to return a function instead of just the value, then you have to call the returned result again just to get the value. 所以要回答你的问题,如果你试图返回一个函数而不仅仅是值,那么你必须再次调用返回的结果来获取值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.