javascript - Scope of this in click handler ECMA script 6 -
this question has answer here:
as scope of this becomes available in es6 arrow functions.
but here case in unable access this in arrow function while working normal anonymous function
example
sample 1
$(document).ready(function() { $('.principal').click(() => { alert($(this).parent().html()); // 'this' undefined here }); }) sample 2
$(document).ready(function() { $('.principal').click(function() { alert($(this).parent().html()); // 'this' available here }); })
the reason jquery explicitly binds this object in click handler element on event captured. way context using standard function, since indeed arrow function ignores binding.
so need either:
- stick standard function callback, or
- use
currenttargetproperty of event object argument jquery passes callback
the latter so:
$(document).ready(function() { $('.principal').click((e) => { console.log($(e.currenttarget).parent().html()); }); }) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div><button class="principal">click me</button></div> outputs:
<button class="principal">click me</button>
Comments
Post a Comment