1

im referring to this: () => {}

I understand arrows functions are new in ES6. I also understand they bind automatically to the parent context using the this keyword

so if I had

class Person {

    classFunc = () => {

    }
}

this would be bound to the parent and I could use this referring to the parent scope automatically

but I sometimes see this in the code () => {}, what does it mean?

for example

onClick={this.handleClick}

or

onClick={() => this.handleClick}

what is that second one doing? is it an anonymous function?

the venom
  • 661
  • 3
  • 9
  • 17
  • Possible duplicate of [Arrow function vs function declaration / expressions: Are they equivalent / exchangeable?](https://stackoverflow.com/questions/34361379/arrow-function-vs-function-declaration-expressions-are-they-equivalent-exch) – VLAZ Nov 01 '18 at 11:04
  • What is that onClicks stuff supposed to be? HTML? That's no valid js. And if it really is HTML, why don't you put your code in quotes? Also, that's no function call without the brackets. – Daniele Torino Nov 01 '18 at 11:12
  • @DanieleTorino actually in react, that would be invoked without the function brackets – the venom Nov 01 '18 at 11:24
  • Really? That seems odd. But I never worked with react so I don't' know about that. – Daniele Torino Nov 01 '18 at 11:28

2 Answers2

0

In second one it will handle the value of callback return by function.

login((res) => {
   console.log(res);    //Hear you will get the res from API. 
})

Before :

login(function(res){
   console.log(res); 
})
Sachin Shah
  • 4,503
  • 3
  • 23
  • 50
-1

ES6 is an updated version of Javascript also know as Javascript 2015. You can find much more about it under this link -

https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/ECMAScript_2015_support_in_Mozilla

Answering your second question -

onClick={this.handleClick}

This will call the function handleClick which is available in the same ES6 class.

onClick={() => this.handleClick}

This will return the function definition and the function will never be invoked. To invoke the function you have to use the call the function.

onClick={() => this.handleClick()}

This will allow you to pass additional arguments if required -

const temp1 = "args1";
.
.
.
onClick={() => this.handleClick(temp1)}

I hope it helps.

Anurag Sharma
  • 241
  • 1
  • 4
  • 13
  • 2
    That's not correct. Without brackets, the first example is not a function call and is, in fact, equivalent to the second example. – Daniele Torino Nov 01 '18 at 11:15