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