Home > Article > Web Front-end > The difference between js arrow functions and ordinary functions
This article mainly introduces to you the difference between javascript arrow functions and ordinary functions. I hope it will be helpful to friends in need!
Arrow functions - a new feature introduced in ES6 - support writing concise functions in JavaScript. Although normal functions and arrow functions work similarly, there are some interesting differences between them, as explained below.
Syntax
Syntax of ordinary functions:
let x = function function_name(parameters){ // 函数体 };
Examples of ordinary functions:
let square = function(x){ return (x*x); }; console.log(sqaure(9));
Output :
Syntax of arrow function:
let x = (parameters) => { // 函数体 };
Example of arrow function:
var square = (x) => { return (x*x); }; console.log(square(9));
Output :
Use the this keyword
Unlike ordinary functions, arrow functions do not have their own this.
For example:
let user = { name: "GFG", gfg1:() => { console.log("hello " + this.name); }, gfg2(){ console.log("Welcome to " + this.name); } }; user.gfg1(); user.gfg2();
Output:
##arguments object availability
arguments objects are not available in arrow functions, but are available in normal functions.Example of ordinary function:
let user = { show(){ console.log(arguments); } }; user.show(1, 2, 3);Output:
of arrow function Example:
let user = { show_ar : () => { console.log(...arguments); } }; user.show_ar(1, 2, 3);Output:
Use the function Ordinary functions created by declarations or expressions are "constructible" and "callable". Since normal functions are constructible, they can be called using the 'new' keyword. However, arrow functions are only "callable" and not constructible. Therefore, we will get a runtime error while trying to construct a non-constructible arrow function using the new keyword.
Example of normal function:let x = function(){
console.log(arguments);
};
new x =(1,2,3);
Output:
let x = ()=> {
console.log(arguments);
};
new x(1,2,3);
Output:
Related recommendations: "
javascript tutorialThe above is the detailed content of The difference between js arrow functions and ordinary functions. For more information, please follow other related articles on the PHP Chinese website!