ES6-7 - 箭头函数的实质、箭头函数的使用场景
生活随笔
收集整理的這篇文章主要介紹了
ES6-7 - 箭头函数的实质、箭头函数的使用场景
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
箭頭函數返回對象
// 這種情況要要用(),否則會將對象的{}解釋為塊 const fn = (a, b) => ({a:1, b:2})箭頭函數的特點
- 所有的內層函數都是箭頭函數,都沒有自己的this,它們的this其實都是最外層foo函數的this。
定義對象的方法
- 定義對象的方法,且該方法內部包括this且該方法內部包括this,不應使用箭頭函數定義
- 以下例子bind與箭頭函數都能讓this指向實例
arguments
function foo() {const a = () => {console.log(arguments)}a() } foo(1, 2, 3, 4) // [1,2,3,4] 箭頭函數內無arguments,取外層的 function foo() {setTimeout(() => {console.log(arguments)}) } foo(1, 2, 3, 4) // [1,2,3,4] 箭頭函數內無arguments,取外層的嵌套的箭頭函數
// 非常語義化 function insert(value) {return {into: function (array) {return {after: function (afterValue) {array.splice(array.indexOf(afterValue) + 1, 0, value);return array;}};}}; }insert(2).into([1, 3]).after(1); //[1, 2, 3] // 改寫為箭頭函數,效果相同但是可讀性差 let insert = (value) => ({into: (array) => ({after: (afterValue) => {array.splice(array.indexOf(afterValue) + 1, 0, value);return array; }})});insert(2).into([1, 3]).after(1); //[1, 2, 3]應用場景
總結
以上是生活随笔為你收集整理的ES6-7 - 箭头函数的实质、箭头函数的使用场景的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ES6-6 - this指向、箭头函数基
- 下一篇: 3481. 阶乘的和