1.作用域
- 全局
- script
- xx.js
- 局部
- 函数作用域
- {} 块作用域 const let
2.闭包
函数外有权访问函数内的变量, 闭包可以延长变量生命周期
function 函数名 () {return function () {// 这里的变量不会立刻释放}
}
3.垃圾回收
-
不在使用(引用的变量), 防止占用内存,需要被自动垃圾回收
-
全局变量: 其他位置可能在使用,不会当成垃圾 除非指定变量不在使用
var user = { name:'zs', age:18 }user = null; // 垃圾回收
-
局部变量: 函数体中的变量
思考? 函数体中变量不回收, 函数调用完成后, 只要该变量不在被引用,
function fn() {var age = 10; }
4.变量提升/函数提升
// 变量提升 提升的变量声明// 变量赋值 不会提升console.log(age);var age = 17;var name = 'ls'function fn () {// 变量提升 当前作用域 最上面var nameconsole.log(name);name = 'zs'}fn();// 函数提升// 函数存在变量提升 函数的声明提升 // 提升有优先级:函数优先级高于变量console.log(fn);function fn() {console.log(1);}var fn = 10;
总结:1. 变量声明提升到当前作用域最上面 2.赋值不会被提升 3. 提升优先级: 函数>变量
5.动态参数
function say (name='东方', age=18) {console.log('名字:',name, '年龄',age);}// say()say('zs', 17)
总结: 调用方法时, 如传参就使用传递的参数 如果没传就使用默认值
6.函数剩余参数
function fn (a, ...args) {console.log(args);}fn(10,20,34);
总结: 1. 剩余参数只能放在形参最后 2. 数组形式存放实参 3. 不计入函数的length
7.箭头函数
// const p1 = new Person()// console.log(p1)const Star = ()=>{// 1. 箭头函数不能使用arguments// 2. 箭头函数没有this 不能使用new 创建对象 箭头函数不能当作类// console.log(arguments);console.log(this);}let _that;function Person () {// console.log(arguments);_that = this;console.log(this);}// Star();// const s = new Star();const s = new Person();console.log(_that == s);// console.log(s, 's')// Person(1,2,3,4,5,'上山');// Star(1,2,3,4,5,'上山')
总结:
1. 箭头函数无this, 不能实例化1. 箭头函数无arguments(伪数组)