闭包
闭包产生的条件:函数嵌套函数,内部函数访问外部函数的变量/函数
闭包产生有两种表现:
- 函数作为参数被传递
- 函数作为返回值被返回
函数中的自由变量,取决于函数定义的地方,跟执行的地方没关系
// 函数作为参数被传递
function fn() {
const a = 10
return function() {
console.log(a); // 10
}
}
const f = fn()
const a = 20
f()
// 函数作为参数被传递
function fn() {
const a = 20
f()
}
const a = 10
function f() {
console.log(a); // 10
}
fn(f)
闭包的作用
- 函数内部变量在函数执行完后,仍然存活在内存中(延长局部变量的生命周期)
- 让函数外部可以操作(读写)到函数内部的数据(变量/函数)
闭包缺点
函数执行后,函数内的局部变量没有释放,占用内存会变长,容易造成内存泄漏。
this指向
谈到闭包不得不说this指向问题是在执行时确认的,定义时无法确认
普通函数、
定时器、
对象方法、
call apply bind、
class、
箭头函数
普通函数
function fn() {
console.log(this); // Window
}
fn()
对象方法
let obj = {
name:'zbt',
run: function() {
console.log(this); // obj, this指向方法调用者
}
}
obj.run()
call apply bind
function fn() {
let arg = arguments // arguments是一个伪元素,不具有数组方法
let arr = [4,5,6]
// 借用数组
// Array.prototype.push.call(arg,4)
// Array.prototype.push.call(arg,arr)
// Array.prototype.push.apply(arg,arr)
// Array.prototype.push.bind(arg,4)()
console.log(arg);
}
fn(1,2,3)
Array.prototype.push.call(arg,arr) 输出结果:
Array.prototype.push.apply(arg,arr) 输出结果:
Array.prototype.push.bind(arg,4)() 输出结果:
call() /apply() /bind() 都可以改变this指向,指向第一个参数
call:参数是单个使用的 参数是一个参数列表,
apply:参数是一个集合时使用,参数是一个数组
bind:使用bind会改变this,不会改变数据,需要在调用的地方加一个括号
class语法糖
class Person {
constructor(name,age) {
this.name = name
this.age = age
}
run() {
console.log(this); // this指向p实例对象
}
}
let p = new Person('小明',19)
p.run()
箭头函数
箭头函数的this是在定义时确定的
this时刻指向父级的上下对象,并且不可以被 call()/apply()/bind()修改
var name = '小明'
let obj = {
name:'小红',
run:()=>{
console.log(this.name);
}
}
let fn = {name:'小小'}
obj.run() // 小明
obj.run.call(fn) // 小明
obj.run.apply(fn) // 小明
定时器
let obj = {
name:'小小',
sun:function() {
// 定时器是Window定义的
setTimeout(function(){
console.log(this); // Window
},1000)
}
}
obj.sun()
装换成箭头函数
// 箭头函数this,定义时确定的
let obj = {
name:'小小',
sun:function() {
setTimeout(()=>{
console.log(this); // obj
},1000)
}
}
obj.sun()