开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第5天,点击查看活动详情
前言:新年伊始,重走ES6之函数扩展。
函数扩展
1.ES5参数的扩展
// ES5中定参数计算
function add(x, y) {
// 严谨的
x = typeof x === 'undefined' ? 1 : x
y = typeof y === 'undefined' ? 2 : y
return x + y
}
console.log(add()) // 3
console.log(add(100, '')) // 100
console.log(add('', 'hello')) // hello
// ES5中不定参数计算
function getSum() {
// console.log(arguments) // 类/伪数组/假数组
let total = 0
for (let i = 0; i < arguments.length; i++) {
total += arguments[i]
}
return total
}
console.log(getSum(10, 20)) // 30
console.log(getSum(5, 10, 15, 20)) // 50
console.log(getSum(10, 20, 50, 1)) // 81
2.ES6参数的扩展
-
形参的位置,通过单引号,赋值即可
-
可变参数:...args收集剩余参数,注意:
- ...只能出现一次
- ...只能发在最后一个形参的位置
- ...的前面,可以有一个或多个固定位置参数
// ES6中
// 定参数计算
function add(x = 100, y = 200) {
return x + y
}
console.log(add()) // 300
console.log(add(100, '')) // 100
console.log(add('', 'hello')) // hello
// 不定参数计算
function getSum(...args) {
let total = 0
for (let i = 0; i < args.length; i++) {
total += args[i]
}
return total
}
console.log(getSum(10, 20)) // 30
console.log(getSum(5, 10, 15, 20)) // 50
console.log(getSum(10, 20, 50, 1)) // 81
3. 箭头函数
箭头函数:
- 语法: const 函数名 = ()=> {}
- 特性:
- 形参只有一个时,可以省略小括号。
- 函数体是有一句话的时候,可以省略大括号,如果省略了大括号, 此时箭头函数自带return的功能,无需自己在显示的时候写return了。
- 注意:不能通过new关键字调用,箭头函数不能视为构造函数。
- 应用场景: 1.多用在回掉函数中 2.改变this指向的时候
// 普通函数写法
// const sayHi = function (name) {
// return `hi~${name}`
// }
// console.log(sayHi('箭头函数'))
// 箭头函数写法
const sayHi = (name) => `hi~${name}`
console.log(sayHi('箭头函数'))
// 箭头函数,this指向、应用场景
const obj = {
name: 'this指向',
age: 18,
fn: function () {
console.log('fn', this)
// 因为this指向window,所以我们使用this赋值方法
// let self = this
// setTimeout(function () {
// console.log('回掉', self)
// })
// 使用箭头函数特性,自动找到离他最近的调用他的上层
setTimeout(() => {
console.log('回调', this) // 下方图片是错别字
})
}
}
console.log(obj.fn())
往期相关精彩文章链接
- ES6查漏补缺【运算符的扩展】
- ES6查漏补缺【数组的扩展】
- ES6查漏补缺【字符串的扩展】
- ES6查漏补缺【var,let,const】
- ES5数组实例方法【forEach】
- ES5数组实例方法【sort】
- 配置ES6的项目环境【Webpack】
相关资料
水平有限,还不能写到尽善尽美,希望大家多多交流,跟春野一同进步!!!