簡體   English   中英

如何在一行中將 iife 舊方式 function 轉換為箭頭 function

[英]How to convert an iife old ways function to an arrow function in a single line

你將如何轉換:

(function(age) {return `your ${age}`;
})(10);

到箭頭 function? 我試過但沒有用:

(const years = (age) => `your ${age}`)(10);

為什么不起作用,如果是因為 const?

然后另一個例子,如果我做:

const marco= { name: 'marco ccc',
  say hi: function () {
  return 'something';
  }
}

如何將 sayHi 轉換為箭頭 function?

我在創建異步閉包時經常這樣做,因此我可以在非異步 function 主體中使用 await。 它看起來像這樣:

(async (arg1,arg2) => {
  console.log(arg1,arg2); // logs a,b
})('a','b');

它使我免於創建一個const然后調用它,如下所示:

const outerFunc = () => {

   // ... some code

   const innerFunc = async () => {
      // I can use await in here
   };
   innerFunc();
}

相反,我這樣做:

const outerFunc = () => {

   // ... some code

   (async () => {
      // I can use await in here
   })();
}

要創建閉包,請省略異步部分

((...args) => console.log(...args))('a','b');

編輯:如果您仔細查看以上內容,您會發現它實際上縮短為

(console.log)('a','b')

表達式被分配給變量。 箭頭函數通常由兩部分組成:分配給它的變量和主體,例如:

const foo = () => { ... }
// ^ variable
            ^^^^ function body

變量的初始化只能作為一個語句,在一個獨立的行上完成; const不能在括號內。 您只需要從(function 主體函數調用)中分離出分配返回值的變量:

 const years = ((age) => `your ${age}`)(10); // ^^^^^^^^^^^^^^^^^^^^^^ // this is the function body // that needs to be invoked immediately // ^^ with the (10) // ^^^^^ with the result assigned to `years` console.log(years);

在 object 中,只需將function()替換為() => (並注意say hi不是 object 文字中的有效 object 屬性 - 要么用引號括起來,要么使用單個單詞):

 const marco = { name: 'marco ccc', sayHi: () => { return 'something'; } }; console.log(marco.sayHi());

所以基本上我想轉換這兩個函數(舊版本):

(function(age) {return `your ${age}`;
})(10);

const marco= { name: 'marco ccc',
  say hi: function () {
  return 'something';
  }
}

console.log(marco.sayHi());

分別轉換為:

((age) => your age is ${age})(10);

const marco= { name: 'marco ccc', sayHi: () => {} }

但除此之外,我還試圖了解 IIFE 的好處,例如:

const years = ((age) => your ${age})(10); 

是比以下內容更短的版本:

const years = (age) => your ${age}; 
const whatever = years(10); 
console.log(whatever);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM