Arrow functions are anonymous; there are only arrow function expressions. You can assign arrow function expression to a variable, can be used in an IIFE as well as a callback function. Below you will find valid arrow functions:
Even if I use
In the below example, when using traditional function,
In order to get the greeting message using the traditional function, there are several ways to keep reference to
or bind with
(a, b) => a + b // implicitly returning a + b
(a, b) => { // explicitly returning a + b
return a + b;
}
a => a * a // omit () when there is one parameter
() => 2 // () mandatory when there are no parameters
(a, b) => { // explicitly returning JS object
return {
a1: a, b1: b
}
}
(a, b) => ({ // implicitly returning JS object
a1: a, b1: b
})
An arrow function does not have its ownIn the example below, when using traditional function,this
.this
in arrow functions is always statically defined by the surrounding lexical scope.
this
refers to the num
object, whereas when using arrow notation, this
is pointing to the global object. Arrow functions doesn't have its own this
, and so this
refers to outer scope, and outer scope for num
object is the window
object.Even if I use
call()
method, result is the same.In the below example, when using traditional function,
this
refers to the global object, whereas using arrow function, we get the desired result.In order to get the greeting message using the traditional function, there are several ways to keep reference to
this
object inside of setTimeOut function. You can create a self
variable like below:const str = {
value: 'Delayed greeting',
greet: function() {
const self = this;
setTimeout(function() {
console.log(self.value);
}, 2000)
}
};
str.greet();
or bind with
this
like below:const str = {
value: "Delayed greeting",
greet: function() {
setTimeout(
function() {
console.log(this.value);
}.bind(this),
2000
);
}
};
str.greet();
It is not possible to use arrow function expression as a function constructor and create new objects from it.
0 comments:
Post a Comment