JS进阶-day1 作用域解构箭头函数
作用域
全局作用域——>尽量少使用,避免变量污染
局部作用域——>函数作用域、块级作用域
作用域链——>底层变量查找机制(先在当前函数作用域查找,如果找不到,就沿着作用域链向上级作用域查找,直到全局作用域)
闭包
概念:一个函数对周围状态的引用捆绑在一起,内层函数中访问到其外层函数的作用域
内存泄露:内存应该被回收却没有回收
闭包=内层函数+外层函数的变量
闭包的作用:
- 封闭数据,实现数据的私有,外部函数也可以访问函数内部的变量
- 闭包很有用,因为它允许将与其所操作的某些数据环境关联起来
闭包可能引起的内存泄露问题
function count() {let i = 0function fn() {i++console.log(`函数被调用了${i}次`)}return fn}const fun = count()
变量提升
使用var关键字声明变量会有变量提升,所有var声明的变量提升到 当前作用域的最前面
变量提升流程:
1.先把var变量提升到当前作用域于最前面
2.只提升变量声明,不提升变量赋值
3.然后依次执行代码
function fn() {console.log(num)var num = 10}fn()
不建议使用var声明变量
函数提升
会把所有函数声明提升到当前作用域前面
只提升声明,不提升函数调用
fn()
function fn() {console.log('函数提升')
}//函数提升后
/*function fn() {console.log('函数提升')
}
fn()*/
fun()
var fun = function () {console.log('函数表达式')
}// 函数表达式 必须先声明和赋值, 后调用 否则 报
函数动态参数
arguments 动态参数 只存在 函数里面
是伪数组 里面存储的是传递过来的实参
function getsum() {let sum = 0for (let i = 0; i < argumrnts.length; i++) {sum += arguments[i]}console.log(sum)
}
getsum(5, 6, 7)
箭头函数
//标准格式
const fn = () => {}
fn()//写在一行上,可省略大括号
const fn = () => console.log(11)
fn() //11//传参只有一个数时,可省略括号
const fn = e => console.log(e)
fn(1) //1//只有一行代码时,可省略return
const fn = e => e + e
console.log(fn(1)) //2//箭头函数可以直接返回一个对象
const fn = (uname) => ({name: uname})
console.log(fn('陈xx'))
普通函数有arguements动态参数
箭头函数没有arguements动态参数,但可以使用剩余参数(...arr)
在开发中【使用箭头函数前需要考虑函数中 this 的值】,事件回调函数使用箭头函数时,this 为全局的 window,因此 DOM事件回调函数为了简便,还是不太推荐使用箭头函数
对象结构
const goods = [{goodsName: '小米',price: 1999}
]
const [{goodsName, price}] = goods
console.log(goodsName)
console.log(price)
多级对象结构
const pig = {name: '佩奇',family: {mother: '猪妈妈',father: '猪爸爸',sister: '乔治'},age: 6
}
// 多级对象解构
const { name, family: { mother, father, sister },age } = pig
console.log(name)
console.log(mother)
console.log(father)
console.log(sister)
console.log(age)