Consider a very simple snippet of HTML and some slightly different methods of assigning an event handler to the HTML SELECT
element. The problem lies with the use of anonymous functions of the form ( e )=>{ alert( this.value ) }
<select name='radius'>
<option>1
<option>2
<option>3
<option>4
<option>5
<option>10
</select>
<script>
/*
this works fine, as you'd expect
*/
const changehandler=function(e){
alert( this.value + ' '+e.target )
}
document.querySelector( 'select[name="radius"]' ).addEventListener( 'change', changehandler );
/*
this works fine using `this` within the event handler when using the more traditional
anonymous function
*/
document.querySelector( 'select[name="radius"]' ).addEventListener( 'change', function(e){
alert( this.value )
});
/*
this does not work as expected. `this` does not refer to the HTML element in this
case - it now refers to `[object Window]`
*/
document.querySelector( 'select[name="radius"]' ).addEventListener( 'change', e=>{
alert( this.value )
});
</script>
I thought I might be able to bind
to the HTML element, like this:
let select=document.querySelector( 'select[name="radius"]' );
select.addEventListener( 'change', e=>{ alert( this ) }.bind( select ) );
This however causes an error Uncaught SyntaxError: missing ) after argument list
So, the question is can I access this
keyword in these new style anonymous functions somehow and for it to refer to the HTML element to which the event handler is assigned? Is there some little trick I have overlooked?