// !细说函数// !1.命名函数function getName(username){return 'Hello' + ' ' + username;}console.log(getName('teddy中国'));// !2匿名函数 没有名字的函数// function (username){// return 'Hello' + ' ' + username;// }// 执行方式1:立即执行函数(IIFE),声明和执行二合一,可以创建作用域,用完就毁了,不会造成风险(function (username){console.log('Hello' + ' ' + username);return 'Hello' + ' ' + username;})('中国111222');console.log(function (username){return 'Hello' + ' ' + username;}('中国'));// 不会给全局带来任何的污染,用来创建临时作用域// 执行方式2:保存到变量中const getName1 = function (username){return 'Hello' + ' ' + username;};console.log(getName1("广东"));// !3箭头函数// 匿名函数:函数表达式,将函数保存到变量中,以后通过变量来引用函数let f1 = function (a,b){return a + b;}console.log(f1(5,6));// 箭头函数:简化函数的申明f2 = (a,b) => a+b;console.log(f2(8,9));f3 = (a,b,c) => a*b*c;console.log(f3(3,5,6));// !函数的使用场景// 1.如果需要多次调用,用命名,函数表达式都可以// 2.如果代码要求:先申明,再调用,必须先用 函数表达式// 3. 如果只是特定的一次性的工作。不想留下痕迹,用IIFE,模块// 4. 如果调用函数需要一个函数充当参数,可以用匿名函数来简化。局限,this
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号