简体   繁体   English

我应该更喜欢函数而不是javascript中的变量吗?

[英]Should I prefer functions compare to variables in javascript?

I saw in particular project this syntax used all the time: 我在特定的项目中一直使用这种语法:

function a() {
    return 'hello';
}
function b() {
    return `${a()} world`;
}
b();

and all variables were almost omitted. 并且几乎忽略了所有变量。 Why just don't use syntax below? 为什么不使用下面的语法?

const a = `hello`;
const b = `${a} world`;
console.log(b);

What advantage has function used to return string compare to const, because I don't see any practical one. 与const相比,用于返回字符串的函数具有什么优点,因为我看不到任何实用的优点。 Only what comes to mine mind is that const b is executed all the time compare to function b which executed only when called. 我唯一想到的是,与仅在调用时执行的function b相比,始终执行const b就一直存在。 Am I missing something? 我想念什么吗?

If the purpose is to provide API path the function approach provide more flexibility. 如果目的是提供API路径,则函数方法可提供更大的灵活性。

IE: IE浏览器:

You can switch environment (test/staging/prod) based on conditions (IE dotENV data). 您可以根据条件(IE dotENV数据)切换环境(测试/分段/生产)。 This is useful when managing base url of your API 这在管理API的基本网址时非常有用

function getENV() {
  switch (process.env.NODE_ENV) {
    case 'production': {
      return URL_PROD;
    }
    case 'staging': {
      return URL_STAGING;
    }
    case 'test': {
      return URL_TEST;
    }
    default: {
      return DEFAULT_URL;
    }
}

Another function can mix the default baseURL with your variable-stored endpoints 另一个函数可以将默认的baseURL与变量存储的端点混合在一起

IE: IE浏览器:

function getEndpointURL(endpoint) {
    return `${getENV()}/${endpoint}`
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我是否应该优先将数组或函数作为JavaScript中的参数传递 - Should I prefer passing the array or the function first as arguments in JavaScript 什么时候我应该更喜欢克隆而不是javascript中的引用? - When should I prefer a clone over an reference in javascript? 什么时候应该使用try / catch而不是函数来在JavaScript中声明非全局变量? - When should I use try/catch instead of functions to declare non global variables in JavaScript? 如何比较 javascript 中的 2 个函数 - how do I compare 2 functions in javascript typescript 访问修饰符和 javascript 访问修饰符有什么区别? 在使用 typescript 时我应该更喜欢哪一个? - What are the differences between typescript access modifiers and javascript ones? And which one should I prefer while using typescript? 在哪种情况下,我应该选择ES6-maps而不是JavaScript对象? - In which cases should I prefer ES6-maps instead of JavaScript-objects? useState、UseRef 或 useMemo,我应该更喜欢哪个 - useState, UseRef, or useMemo, what should I prefer 我什么时候应该在 Javascript 中将函数用作类? - When should I use functions as classes in Javascript? 我应该测试Javascript插件的私有功能吗? - Should I test the private functions of a Javascript plugin? 我应该在Java代码中的哪个位置放置函数? - Where should I put functions in Javascript code?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM