“此"将箭头函数与jQuery回调一起使用时,关键字的行为有所不同 [英] "this" keyword behaves differently when using arrow functions with jQuery callbacks
问题描述
我有一个包含多行的表,并且每行上都有一个edit
和delete
按钮.
简而言之,当使用类.edit
触发编辑按钮时,将弹出一个表单.除了类名之外,我还包括一个独特的id
,例如id="edit-32"
,其中数字根据用户单击的行而变化.
我要解决的问题是在破折号后捕获id属性编号.以前,在ES5中,我仅使用this
键盘来定位要单击的当前元素.但是在ES6中,this
关键点指的是类环境.
ES5方法(返回唯一ID)
// Open edit form
$('.edit').click(function(){
// Return id attribute
const id = $(this).attr('id');
// print to console
console.log(id);
});
ES6方法(返回未定义)
// Open edit form
$('.edit').click(() => {
// Return id attribute
const id = $(this).attr('id');
// print to console
console.log(id);
});
有没有一种方法可以使箭头功能与ES5相似?
普通函数中的 this
解析为调用该函数的对象,因此在这种情况下,this
是被单击的元素.>
箭头函数中的
this
并未定义其自己的this
,而是使用了封闭执行上下文的this
值.
在这种情况下,它不能与箭头功能一起使用.您必须坚持使用标准功能.
I have a table with multiple rows, and on each row, there is an edit
and delete
button.
In short, when an edit button is triggered with class .edit
, a form pops-up. Along with the class name, I have also included a unique id
like id="edit-32"
, where the number changes depending on what row the user clicks on.
The problem I am trying to solve is to capture the id attributes number after the dash. Previously, in ES5, I have simply used this
keywoard to target the current element being clicked. But in ES6, this
keywoard is refereing to the class environment.
ES5 approach (returns unique ID)
// Open edit form
$('.edit').click(function(){
// Return id attribute
const id = $(this).attr('id');
// print to console
console.log(id);
});
ES6 approach (Returns undefined)
// Open edit form
$('.edit').click(() => {
// Return id attribute
const id = $(this).attr('id');
// print to console
console.log(id);
});
Is there a way I can make arrow functions work with similar approach to ES5?
this
in normal functions resolves to the object that calls the function, so in this case, this
is the element that is clicked on.
this
in arrow functions does not define its own this
, instead the this
value of the enclosing execution context is used.
It won't work with arrow functions in this case. You'll have to stick to bog standard functions.
这篇关于“此"将箭头函数与jQuery回调一起使用时,关键字的行为有所不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!