Key differences between arrow functions and normal functions:
- Arrow functions do not have this (the main difference between arrow functions and normal functions).
- Arrow functions have no prototype
- Arrow functions have no argements(array of classes)
1. The orientation of this (the main difference between arrow functions and ordinary functions)
(1) Arrow function does not have this, its this is inherited from the parent context, and can not use call, apply, bind to change the point of this, arrow function this will never change.
For example, the arrow function this.x, the arrow function and say level are in the form of key:value, that is, the arrow function itself is in obj, and the parent execution context of obj is window, so this.x here actually represents window.x, so output 11.
var x = 11;
var obj = {
x:22.say:() = >{
console.log(this.x);
}
}
obj.say();/ / 11
Copy the code
(2) The ordinary function this refers to its direct caller.
// A normal function
var name = "ice";
var obj = {
name: "leaf".getName: function() {
console.log(this.name);// This refers to its right-angle caller, which is obj, so return leaf}}; obj.getName();// point to the caller obj and print leaf
// Arrow function
var name = "ice";
var obj = {
name: "leaf".getName: () = > {
console.log(this.name);
Name is created in the global context, and this refers to the global object}}; obj.getName();//ice
var obj1 = { name: "haha" };
obj.getName.call(obj1); // Can't change whether this points to the output or ice
Copy the code
The arrow function has no prototype and cannot be called as a constructor.
// A normal function
function Person() {
console.log("person");
}// Define a constructor
const myFather = new Person();// Constructor instantiate object
// Arrow function
let Person2 = () = > {
console.log("person2");
}
console.log(Person2.prototype);//undefined
const myFather2 = new Person2();////Person2 is not a constructor
Copy the code
Arrow functions have no argements and can only be based on… Arg to get the set of parameters (array)
let Person2 = () = > {
console.log(person2.argements);
}
Person2(10.20.30)// Person3 is not defined
// Only... Arg to get the set of parameters (array)
let Person2 = (. arg) = > {
console.log(arg);
}
Person2(10.20.30)/ / [10, 20, 30]
Copy the code
Continue to supplement the update, the record is not good at the point of revision, common progress ~