0

I am converting one of my old javascript code to ECMA6. Getting problem in passing "this" in the callback to the "addEventListener" method.

Here is my HTML,

<p><span id="temperature"></span><span id="degname">C</span></p>

In My Javascript I am making this span element a clickable element. In my old code "this" is passed nicely in the callback and it is pointing to the "span" element but in the ECMA6 code "This" is pointing to the "window" object.

I researched about the issue. There is a option of using bind function to the callback in ECMA6 to pass the "this" pointer but I want to use the anonymous callback.

Could anyone please tell how can I pass the parent object(here "span" element) "this" pointer to the anonymous callback ?

Here is my old code,

document.getElementById("degname").addEventListener("click",function(){
  //alert("hello fahrenhite");
  console.log("the value of this = "+this); **//"this" is here the span element**
   var name = this.innerHTML;
   console.log("name is : "+name); //name is giving right value


   });

and here is the ECMA6 :

document.getElementById("degname").addEventListener("click",() => {

    console.log("The value of this = "+this); **//"this" is here is windows object**
    let name = this.innerHTML; **//name is here undefined**

   });
sandy
  • 283
  • 1
  • 7
  • 27
  • 1
    Use `event` parameter and check `event.target`, or save the element in a variable first, then reference it in the handler – CertainPerformance Mar 23 '19 at 18:56
  • 1
    Use `event.currentTarget` to get the element that would be bound to `this`. That way, you'll still get the correct element if there are nested elements that are clicked. – ziggy wiggy Mar 23 '19 at 18:59
  • @ziggywiggy , ... thanks for your answer. This solved the issue. But could you please tell why "this" is not working as current context in ECMA6 ? I am learning ECMA6 new. So, wanted to know how this feature is defined and what it is called so that I can use it rightly next time. – sandy Mar 23 '19 at 19:07
  • Arrow functions simple do not bind a `this` value. It just doesn't exist directly in that function, so instead it gets the closest "outer" one it can find, in a way similar to the way variables are fetched from outer scopes. – ziggy wiggy Mar 23 '19 at 19:10

0 Answers0