Essentially, there is no difference.
This has nothing to do with React, though.
Arrow functions are a relatively new feature added to Javascript that give you a way of defining functions in a more concise way.
function foo (param1, param2, etc) {
// do something
}
// becomes
var foo = (param1, param2, etc) => {
// do something
}
If you have only 1 param, you don't need the parantheses:
function foo (param) {
// do something
}
// becomes
var foo = param => {
// do something
}
If there is only 1 expression, and the result is returned, you can omit the {}
too!
function foo (param) {
returns param * 2
}
// becomes
var foo = param1 => param * 2
this
is not not updated
In an arrow function, you don't get a new this
- it is the same as in the parent block. This can be useful in some cases (when using setTimeout
, for example)
In ES6 we can also use the class
keyword to define "classes" in Javascript. They still use prototype, though!
function Something (foo) {
this.bar = foo;
}
Something.prototype.baz = function () {
return baz * 2
}
// becomes
class Something {
constructor(foo) {
this.bar = foo;
}
baz () {
return baz * 2
}
}
So the constructor is done in constructor()
and all the following methods are added to the Prototype. It's nothing but syntactic sugar (but kinda does some of the Prototype heavy lifting for you)
You can use extends
!
class SomethingElse extends Something {
constructor(foo, lol) {
this.lol = lol
// Use super() to call the parent's constructor
super(foo)
}
baz () {
return baz * 2
}
}