preface
Function and arrow functions are an age-old problem. I’ve been told since I first started javaScript that you can avoid 80% of the problems by using arrow functions instead of function directly, and this is true in practice. In all the complicated function callbacks, If you do not use the arrow function, it will lead to the error of this pointing to the program. (Of course, you can also use the call Function to change this, but this greatly increases the operation cost.)
This year rare free touch fish want to talk about this topic, but also to help their ideas.
The difference between
The most intuitive difference between function and arrow functions is the way they are created
Function A() {console.log(this)} B = function () {console.log(this)} C = () => { console.log(this) }Copy the code
Call, bind, and apply are not considered in this case:
- Function This is specified when used. (When creating a function function,this is undefined. This refers to the caller only when the function is called.)
- The arrow function’s this is specified when it is created. (When the arrow function is created, bind the current this for the current context, and the function can access the context in which it was created later.)
We use the browser console for debugging
Manufacturer {b: ƒ} objectB = {b: ObjectC = {C: C} objectc.c () {C: C} objectc.c ();Copy the code
The function function’s this points to its caller, while the arrow function’s this points to no caller.
Object creation
We know that in JS, we can use the new function function to create objects, but not the new arrow function to create objects.
// Uncaught TypeError: C is not A constructor new C()Copy the code
Why can’t you create an object using the new arrow function?
Function () {function () {function () {function () {function () {function () {function () {function () {function () {function () {function ()}}}}}}}}}}}}}}}}}}}}}}}}}}}} The new keyword cannot be used to create arrow functions that are bound to this at the time of creation.
Although we can’t create objects through the new arrow function, we can create objects through the Object Prototype function, which is perfected later
Return object.create ({},C); // After executing the arrow function, the Object inherits the prototype chain of function.Copy the code
conclusion
It is not hard to see that the original purpose of function function is to create objects, so we use function function when ordinary functions are called on the Web side, it is easy to have various problems, and the arrow function in the back solves this problem to a large extent. Therefore, I recommend using the function function when creating objects and only the arrow function when executing methods in future code. It makes writing code a lot clearer.
Afterword.
On the other hand, with the es6 syntax, you can say that the hash arrow function is fine, and that the function function is relegated to history. (Personal opinion only, strong desire for life)