Difference: 1. The writing method is different. The ES6 arrow function is "() => {}" and the ES5 function is "function funName(){}"; 2. The let binding is different. When there is only one function When taking parameters, the arrow function can omit the parentheses. When the function only returns a value, the arrow function can omit the curly braces. 3. This points to different points. The es5 function points to the object to which the function is called, while the arrow function points to the point of this when it is defined. That is, pointing to the global window object.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
es6 Arrow Function
The arrow function is a new representation of functions in es6. It takes the simplicity of functions to the extreme! Let’s first look at the simplest arrow function:
let fn = a => a var m = prompt() alert(fn(m))
People who are exposed to arrow functions for the first time may be surprised by its concise syntax! Let’s compare it with the syntax of es5
let fn=function(a){ return a; } var m = prompt() alert(fn(m))
The difference between es5 functions and es6 arrow functions
ES3 and ES5 ordinary functions: function a(){}
ES6 arrow function: () => {};
For example, use the map method to map the original array " Mapping" into the corresponding new array:
//ES3,ES5写法 var a = [1,2,3,4,5]; var b = a.map(function(i) { return i + 1 }); console.log(a,b);
Console result
##
//ES6写法 let a = [1,2,3,4,5]; let b = a.map(i => i + 1) console.log(a,b);
Summary: Arrow functions and ordinary functions are bound to let; when the function has only one parameter, the parentheses can be omitted, and when the function only returns a value, the curly braces can be omittedThen~here I would also like to talk about the arrow function this pointing issue. Note: Ordinary function this points to: the object to which the function is called, arrow function: the point of this when defined (points to the global window object) Another example:
//ES3,ES5 function foo(){ this.a = 'a'; this.b = 'b'; this.c = { a: 'a+', b: function() { return this.a } } } console.log(new foo().c.b()); //ES6 function foo2(){ this.a = 'a'; this.b = 'b'; this.c = { a:'a+', b:() => { return this.a } } } console.log(new foo2().c.b());
javascript video tutorial, programming video】
The above is the detailed content of What is the difference between es5 function and es6 arrow function?. For more information, please follow other related articles on the PHP Chinese website!