声明函数的5种方式
第一种方式: 具名函数
function fn(arg1,arg2,arg3,...) {}
第二种方式: 匿名函数
let fn = function() {}
第三种方式: 具名函数表达式
let fn = function a() {}
这种方式的函数名只在函数作用域内起作用
第四种方式: window.Function()
let fn = new Function('x', 'y', 'return x + y')
基本没人用的方式
第五种: 箭头函数
let fn = (x, y) => {
return x+y
}
箭头函数当只有个函数的时候可以省略括号, 只有一个语句的时候可以不带{}
, 并且函数会自动return
这个语句的值
let fn = x => x**2
fn(2) //4
箭头函数不绑定this
如何调用函数
假设我们声明了一个fn函数
function fn() {}
记住,请用fn()
调用. 一定要带括号才是函数调用, 可能有人觉得这很简单啊, 好, 再来一个
fucntion fn() {
return fn2() {}
}
fn()()
才是调用fn2
不过其实还是建议用call
来调用函数
如第一个我们可以用fn.call(undefined)
来调用函数fn
this和arguments
-
this
就是call的第一个参数 -
arguments
就是call的第二个开始到最后的参数
'use strict' //严格模式
f= function() {
console.log(this)
console.log(arguments)
}
f.call(undefined,1,2,3)
//undefined
//伪数组[1,2,3]
调用栈
用这个网站自己试吧, 反正不好讲
Loupe
作用域
![](https://img.haomeiwen.com/i8412690/be99943665180f44.png)
网友评论