[英]Should I prefer passing the array or the function first as arguments in JavaScript
[英]Should I prefer functions compare to variables in javascript?
我在特定的項目中一直使用這種語法:
function a() {
return 'hello';
}
function b() {
return `${a()} world`;
}
b();
並且幾乎忽略了所有變量。 為什么不使用下面的語法?
const a = `hello`;
const b = `${a} world`;
console.log(b);
與const相比,用於返回字符串的函數具有什么優點,因為我看不到任何實用的優點。 我唯一想到的是,與僅在調用時執行的function b
相比,始終執行const b
就一直存在。 我想念什么嗎?
如果目的是提供API路徑,則函數方法可提供更大的靈活性。
IE瀏覽器:
您可以根據條件(IE dotENV數據)切換環境(測試/分段/生產)。 這在管理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;
}
}
另一個函數可以將默認的baseURL與變量存儲的端點混合在一起
IE瀏覽器:
function getEndpointURL(endpoint) {
return `${getENV()}/${endpoint}`
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.