0

I'm new to javascript, and I saw code like this.

<button onclick="this.onClickDoSmth">Click me</button> 

onClickDoSmth = () => {
let a = this.clicked();
a();
}

clicked = () => {
console.log("test"); 
}

What's the difference of replacing the expression for "a" to

onClickDoSmth = () => {
this.clicked();
}

3 Answers3

0

First a correction is required. It should be let a = this.clicked; instead of let a = this.clicked(). The former means you're assigning the returning function to the variable a and executing it later with a(). So if you do this way, there's no difference.

onClickDoSmth = () => {
    let a = this.clicked; //This has to be corrected
    a();
    }

    clicked = () => {
    console.log("test"); 
    }
ABGR
  • 4,631
  • 4
  • 27
  • 49
0

The difference is that the former version received something from the function while the latter one doesn't.

This means the value of a receive what this.clicked function return. this.clicked must return a function so that it can be called by a() afterward

onClickDoSmth = () => {
    let a = this.clicked();
    a();
}


This means onClickDoSmth is a function. After it has been executed, run this.clicked

onClickDoSmth = () => {
   this.clicked();
}
tcf01
  • 1,699
  • 1
  • 9
  • 24
-1

The former uses assigns a function and calls that variable if you want to reuse again. The latter just calls the function immediately. Both will achieve the same output.

Andrew Halpern
  • 514
  • 3
  • 6