0

I have some struggle to understand how the arrow functions in JS actually work.

Please consider this snippet

  editButton.onclick = () => this.edit(input);

    edit(input){
        input.disabled = !input.disabled;
    }

Why does that work but this here not?

  editButton.onclick = function() {
            this.edit(input);
        }
    }

    edit(input){
        input.disabled = !input.disabled;
    }

Not the same? If I replace this.edit(input) with console.log("Test"); it works on both but this.edit(input) somehow not, why is that so? I mean () =>is basically function() { }no??

Haidepzai
  • 764
  • 1
  • 9
  • 22
  • because the "this" object has no more the same meaning – Alberto Sinigaglia Mar 11 '20 at 21:18
  • the "this" has not the same meaning in arrow functions or in normal functions – Pac0 Mar 11 '20 at 21:18
  • 1
    Obviously, `this.edit` is a property of a class or constructor, so within an arrow function it scopes up to the constructor. `this` within an EventListener, assigned a normal function, scopes to the Element. – StackSlave Mar 11 '20 at 21:21

0 Answers0