Skip to content

Function 函数

声明方式

  1. 构造函数声明
js
const handle = new Function('console.log(`hello world!`)')
  1. 字面量方式声明
js
function handle() {
  console.log('hello world!')
}
  1. 赋值方式声明
js
const handle = () => {
  console.log('hello world!')
}

const handle = function() {
  console.log('hello world!')
}

箭头函数

匿名函数可以省略函数名和括号,直接写函数体。

匿名函数改写为箭头函数

js
const handle = function() {
  console.log('hello world')
}
const handle = () => {
  console.log('hello world')
}
// 函数体只有一行可以省略{}
const handle = () => console.log('hello world')

// 参数只有一个时,可以省略()
const handle = a => console.log(a)

递归

  • 阶乘
js
function factorial(num) {
  return num === 1 ? 1 : num * factorial(--num)
}
factorial(5)
  • 求和
js
;[1, 2, 3, 4].reduce((a, b) => a + b)
// 递归实现
function sum(...args) {
  return args.length == 0 ? 0 : args.pop() + sum(...args)
}

console.log(sum(1, 2, 3, 4))

递归需要确保每次接收到的参数的结构是一致的 原因: 递归是重复做一件事,当条件达到时退出

回调函数

在其他函数中调用的函数就是回调函数

js
document.getElementById('app').addEventListener('click', () => console.log('click'))

() => console.log('click')部分是回调函数

展开语法 ...

... 在表达式右侧就是展开,在表达式左侧就是合并

js
function sum(...args) {
  return args.reduce((a, b) => a + b)
}
console.log(sum(1, 2, 3, 4))
js
// 展开语法放置于最后一个形参
function sum(discount = 0, ...products) {
  return products.reduce((a, b) => a + b) * (1 - discount)
}
sum(0, 100, 200, 300)

函数中的 this

  • 对象中的方法就是当前对象
js
const obj = {
  name: 'wxw',
  show() {
    return this.name
    // this 指向当前对象
  },
}
console.log(obj.show())
  • 全局环境中 this 就是 window
js
console.log(window)
console.log(this)
// 全局环境中 this 和 window 一致