let f = (a, b) => `${a}+${b}=${a + b}`console.log(f(1, 2))console.log('----------------')
f = (a, b = 10) => `${a}+${b}=${a + b}`console.log(f(1))console.log('----------------')
f = (a, b, ...arr) => arrconsole.log(f(1, 2, 3, 4, 5))f = (...arr) => arrconsole.log(f(1, 2, 3, 4, 5))f = (...arr) => arr.reduce((acc, cur) => acc + cur)console.log(f(1, 2, 3, 4, 5, 6))// ? ... 用在参数中是压入数组,用在数组中是"展开"操作let args = ['HTML', 'css', 'js']console.log(`已学了 ${[...args]} 课程`)console.log('=========================')
function a() {return 'aaa'console.log('bbbb')}console.log(a())// ?其实""多值返回"还是返回单位,只不过返回的是一个集成或数组的"引用类型"// ?常用多值返回的引用类型:数组 和对象,或二都兼有// 1. 返回一组商品信息const items = () => [{ id: 1, name: '笔记本' },{ id: 2, name: '打印机' },{ id: 3, name: '手机' }]console.log(items())// 2. 对象返回一些信息// 模板封装(IIFE)立即执行函数const user = ((uname, email) => ({uname,email,print() {return `${this.uname}:${this.email}`}}))('老李', 'nx99@qq.com')console.log(user.uname)console.log(user.email)console.log(user.print)
为什么要多此一举呢,为什么不直接定义一个user对象呢?
- 立即执行函数创建的是临时作用域,不会污染全局环境,(对全局隐身)
- 用户拿到时,模块已经有了初始状态,即已具备可用的属性和方法
- 对于用户来说,模块是一个对象,其实模块是一个函数
- 函数是有作用域的,所以模块也有了作用域,关于模块作用域,后面有介绍
- 实际工作的模块比这个复杂的多,更多采用””注入式”,感兴趣同学,可以进阶
1.参数不足:默认参数
2.参数过多: …rest
3.多值返回: 数组,对象
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号