current position:Home>JS anonymous function, () = & gt; ({}) Usage and meaning of

JS anonymous function, () = & gt; ({}) Usage and meaning of

2021-08-27 06:07:53 A Tao

One 、{} Surround objects object; Surround code blocks code block ( Such as method body , Or ordinary code blocks )

Two 、() Enclose the parameter list ; As a self calling expression , Surround some need The result is obtained by operation Code for ( among The enclosed code will execute once ). Function expressions can call themselves ( That is, it runs automatically once ). If the expression is followed by (), Automatically called . You cannot call a declared function , By adding parentheses , To show that it's a function expression .

fucntion foo() { console.log('hello world') ; } // Declare a function  foo() 
foo() // Call this function 
(function bar () {console.log( 'hello you'); }) () //  Self calling function   And immediately performed once  
bar //  Report errors    Undefined 
bar () // Report errors    Undefined 
 Copy code 

3、 ... and 、 Arrow function

  • Arrow function expression (ES6) The return value of
    Arrow function expression x => x, Express function(x) {return x;}.
    But if The return value is object type , Cannot be x => {name:'JT'},, Need to be changed to x => ({name:'JT'}).

    getObj = (name) => {someone:name}; // getObj('fyy') Cannot get object return value , by undefinedgetObj = (name) => ({someone: name}); //getObj('fyy') Get the return value of the object , by {name:'fyy'} // in addition , In the use of typeof When viewing the type of arrow function expression , You can also see () The role of . typeof x => x // Grammar mistakes . typeof (x => x) // "function". Use () Run the arrow function expression as a result | Return value . The return value is a function . And then use typeof Judge .

  • Create an anonymous function and execute it immediately

    // function(str) {return str;} // Report errors :Uncaught SyntaxError: Unexpected token (

    // use () Enclosing code snippets . Become a function . (function(str) {return str;}) // Function followed by (...args), The resulting function will execute once . (function(str) {return str;})(" test ")

    // Get function func = (function(str) {return str;}) // Get the return value of the function directly retValue = (function(str) {return str;})(" test ");

copyright notice
author[A Tao],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827060751147m.html

Random recommended