Today, we will go over some interesting topics for review. Now that spring break has started, I will try to blog more regularly!
IIFE stands for Immediately invoked function ｅxpressions, and it is a function expression that can be called immediately.
To study IIFE with detail, there are two things to compare. Function Declaration and Function Expression.
Function declaration refers to the below.
Function expression is to assign a function to a variable.
Function is assigned to variable so it is carried out without having to be saved to variable object. It is carried out in runtime instead. Function declaration has the potential for JS interpreter to save too much code to the variable object and cause the response speed to slow down.
In addition, anything declared in global scope can be accessed anywhere in the code. Methods and properties that should not be shared and variables that are declared elsewhere with the same name need to be considered.
Immediately invoked function does not required a function to be defined or saved to a variable. Wrapping a function with brackets make it a immediately invoked function. Using IIFE does not require you to decalre a variable globally and prevent any conflicts between global variables.
Arrow function expression is shorter compared to other function declaration and it doesn’t bind its this, arguments, super or new.target. It is also anonymous it cannot be used as a creator and is appropriate when it is not used as a method function.
Two functions above are the same!
The biggest advantage of arrow function is that code can be more brief and concise. It can also be used as a callback function, so many examples in MDN use arrow functions.
Arrow function is used anonymously, so a function expression is used to call arrow function.
Originally, “this” of a function is decided by where it is called (dynamic scoping), but using an arrow function does not require separate binding and does not create its own “this”. It inherits the “this” of the context that includes itself. An arrow function always points at “this” of the higher scope. It is simlar to lexical scope. Using call, apply or bind will also not change “this”.
Arrow function also has disadvantages. Since “this” of an arrow function points at the context of the higher scopethat contains itself, it is not good to be used as a method function.
When we call the function above, we may think 55 would show as an answer. However, the “this” of the arrow function does not point at the object “age”, but points at the higher context, which is the global object window. Therefore, the result of the function is “Hi undefined”.
Prototype uses “this”, so the same problem occurs. Arrow function cannot be used as a constructor function because it does not have the prototype property.
addEventListener should not use an arrow function as the callback function because this would point at the window.
The cases above should use a normal function.