Page:
2_improving_readability_with_arrow_functions
2
2_improving_readability_with_arrow_functions
jason.zhu edited this page 2021-05-12 12:27:54 +10:00
Module 2: Improving Readability with Arrow Functions
Objectives:
- Arrow Functions - What and Why
- Defining Arrow Functions
- Behavior of
this
Keyword
Introducing Arrow Functions
Feature of Arrow Functions
- Introduced in ES6
- Simpler way to write a function expression
- Why to use them?
- shorter syntax
this
derives its value from enclosing lexical scope
Writing Arrow Functions
Function 1
Transfer Regular Function 1
let greetings = function() { // anonymous function
return 'Hello World!';
};
let message = greetings();
console.log(message); // Hello World!
to Arrow Function
let greeting = () => {
return 'Hello World!';
};
let message = greetings();
console.log(message);
to Simplified Arrow Function
let greeting = () => 'Hello World!';
let message = greetings();
console.log(message);
Function2
let greet = function greetings(name) {
return 'Hello ' + name;
}
console.log(message);
to
let greeting = name => 'Hello ' + name;
let message = greetings('John');
console.log(message);
Bahavior of this
Keyword
this
of regular function:
- refers to the owner of the function we are executing
- for standalone function,
this
refers global window obj - for function within object,
this
refers the object
- for standalone function,
this
of arrow function
- Unlike regular functions, arrow functions do not have their own
this
value
Demo
let message = {
name: 'John',
regularFunction: function() {
console.log(this);
},
arrowFunction: () => console.log(this)
}
message.regularFunction(); // {name: "John", regularFunction: f, arrowFunction: f}
message.arrowFunction(); // {window: Window, self: Window, document: document, name: "", ...}