简体   繁体   English

在函数内返回函数vs语句之间的区别

[英]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.

相关问题 语句和功能之间的区别 - Difference between statement and function 在类外部调用函数与在内部调用函数有什么区别? - What is the difference between invoking a function outside of class vs inside of it? 调用函数与返回函数调用-区别? - calling a function vs returning the function call - difference? 在RequireJS中定义模块时,返回对象与返回init()函数之间有什么区别? - When defining module in RequireJS, what's the difference between returning an object VS returning an init() function? 在递归期间返回 function 调用与仅调用 function 有什么区别? - What is the difference between returning a function call vs only calling the function again during recursion? 在promise中返回promise和返回undefined之间的区别 - Difference between returning a promise vs returning undefined inside a promise 将语句放在 () 中 (function{}) 和将语句放在 (function{}) 中的区别 - difference putting statement in the () in (function{}) and putting statement inside the(function{}) 有和没有return语句的函数之间有区别吗? - Is there a difference between a function with and without a return statement? 分配给函数内部和函数外部的属性有什么区别? - What is difference between properties assigned to function inside of function and outside the function? JS Module: Difference between directly returning a function in an object and returning a function in an object returning a function - JS Module : Difference between directly returning a function in an object and returning a function in an object returning a function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM