Javascript objects may not be expressed with the rocket syntax like Ruby's hashes.
However, as ECMAScript 6 is adopted, Javascript implementations have gained the ability to use the same symbol, =>
for anonymous function definitions, though they are referred to as arrow functions or colloquially as fat arrows rather than hash rockets.
For simple functions, there is no difference between definitions with the arrow syntax and traditional functions.
var foo = function (s) { return s.toString() }
and
function foo(s) { return s.toString() }
are equivalent to:
var foo = (s) => { return s.toString() }
additionally, these are both equivalent to:
var foo = (s) => s.toString()
as well as:
const foo = s => s.toString()
However, when using this
, the choice between traditional and arrow functions matters, as traditionally defined functions create a new scope for this
, whereas arrow functions do not. Examples from the Mozilla doc on Arrow functions by Mozilla Contributors (licensed under CC-BY-SA 2.5):
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
Here, p.age
will always be 0 because the age
that is incremented belongs to a this
which only exists within the inner function, not the instance of Person
which is p
. When the inner function is defined as an arrow function:
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(() => {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
p.age
will be equal to the number of seconds since p
was created because the this
in inner function is the instance's this
.
For more information, please refer to the Mozilla docs.