函数

1.函数的五种声明方式

变量声明可以是Number String Boolean null undefined Symbol Object
而函数只能是 函数

  • 具名函数
  • 匿名函数
    匿名函数不能单独使用,使用前要声明一个变量,把它赋给变量
  • 第三种
    1
    2
    function y(){}
    console.log(y) // 可以直接调用
1
2
var x = function y(){}
console.log (y) //y不能被调用,调用仅限在{}内部可以调用

这两个具有不一致性,面试经常会问

  • window.Function
    image.png

  • 箭头函数
    image.png
    省略{}要连return一起省略不能只省略一个
    箭头函数没有名字

2.name

没什么用的属性
image.png
new Function的名字就是anonymous,匿名的

1
2
var f1 = function f2(){}
f2.name为undefined

3.函数到底是什么

函数就是可以反复使用的代码块。函数可以接受输入的参数,不同的参数会返回不同的值。

  • f与f.call()的区别
    f只是一个对象
    f.call是执行这个函数体
    f(1,2) <——> f.call(undefined,1,2)
    只准使用后者,后者才是真正的调用,第一个参数必须是undefined

  • this,arguments
    f.call(undefined,1,2)其中undefined就是this,1,2就是arguments
    call的第一个参数可以用this
    call后面的参数可以用arguments

    1
    2
    3
    4
    5
    6
    7
    8
    9
    f = function(){
    'use strict' //严格模式
    console.log(this)
    console.log(this===window) //严格模式下等于undefined,非严格模式等于window
    }
    返回
    f.call(undefined)
    false //严格模式下返回false,非严格模式返回ture
    undefined
  • call stack 调用栈
    先进后出
    image.png
    stack overflow 站溢出,这也是一个网站,可以用来解决bug的问题

3.作用域

1
2
3
4
5
6
7
8
9
10
11
12
var a =1    //所在区域为全局scope,全局作用域
function f1(){ //理解为所在区域为二级作用域
console.log(a)
var a =2
f2.call()
function f2(){ //理解为三级作用域
var a = 3
console.log(a)
}
}
f1call()
console.log(a)

4.闭包

如果一个函数使用了他范围外的变量,那么(这个函数+这个变量)就是闭包