我认为箭头函数“仅仅”是一个反义函数的快捷方式,所以我一直在使用它。但是,最近我遇到了一个箭头函数引起一些问题的例子。下面是一个示例代码: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)实现同样的事情吗?或者在这种情况下不可能实现?
谢谢!
的可能的复制[箭职能及本(http://stackoverflow.com/questions/28798330/arrow-functions-和 - ) –
[在JavaScript中,“=>”(等于和大于等于一个箭头形成的箭头)的含义可能重复吗?](http://stackoverflow.com/questions/24900875/whats-the-meaning-的-的箭头形ed-from-equals-more-in-javas) – 2016-08-24 13:50:48
有人有一个糟糕的一天?在不留下评论的情况下下调好的答案。如果这些是战略性的downvotes ...以及如果它意味着你这么多:) – Michelangelo