2016-08-24 72 views
0

我認爲箭頭函數「僅僅」是一個反義函數的快捷方式,所以我一直在使用它。但是,最近我遇到了一個箭頭函數引起一些問題的例子。下面是一個示例代碼:ES6,箭頭函數,「this」的上下文

function refreshTable() { 
    $.ajax({ 
    url: root + `/posts?userId=${userId}`, 
    method: 'GET' 
    }).then(function(data) { 

    for (var item of data) { 
     $('table.list tbody').append(` 
      <tr> 
       <td>${item.id}</td> 
       <td>${item.title}</td> 
       <td>${item.date}</td> 
       <td> 
       <a href="" data-id="${item.id}" class="getDetails">View</a> | 
       <a href="" data-id="${item.id}" class="getDetails">Delete</a> 
       </td> 
      </tr> 
      `); 
    } 

    $('.getDetails').click((e) => { 
    // $(this) is actually the ajax call, I can't access the "data" part 
    }); 

    }); 
} 

然而,這個工程:

function refreshTable() { 
    $.ajax({ 
    url: root + `/posts?userId=${userId}`, 
    method: 'GET' 
    }).then(function(data) { 

    for (var item of data) { 
     $('table.list tbody').append(` 
      <tr> 
       <td>${item.id}</td> 
       <td>${item.title}</td> 
       <td>${item.date}</td> 
       <td> 
       <a href="" data-id="${item.id}" class="getDetails">View</a> | 
       <a href="" data-id="${item.id}" class="getDetails">Delete</a> 
       </td> 
      </tr> 
      `); 
    } 

    $('.getDetails').click(function(e) { 
    // $(this) is the HTML element, so I can access "data" 
    }); 

    }); 
} 

顯然,有一些邏輯箭頭的功能,它創造了this不同的範圍。發生什麼了?我能用箭頭函數(訪問HTML)實現同樣的事情嗎?或者在這種情況下不可能實現?

謝謝!

+1

的可能的複製[箭職能及本(http://stackoverflow.com/questions/28798330/arrow-functions-和 - ) –

+0

[在JavaScript中,「=>」(等於和大於等於一個箭頭形成的箭頭)的含義可能重複嗎?](http://stackoverflow.com/questions/24900875/whats-the-meaning-的-的箭頭形ed-from-equals-more-in-javas) – 2016-08-24 13:50:48

+1

有人有一個糟糕的一天?在不留下評論的情況下下調好的答案。如果這些是戰略性的downvotes ...以及如果它意味着你這麼多:) – Michelangelo

回答

0

那麼你正在體驗到什麼是箭頭功能。它從詞法或父範圍中取得thishttp://exploringjs.com/es6/ch_arrow-functions.html

其次,它們是從環境中拾取的(詞彙)。因此,您不再需要bind()或this = this。

是的,你可以使它工作,但你需要把HTML元素放在點擊功能之外。然後你可以在功能裏面使用this,而不用使用他自己的this

相關問題