1,在函数外部获取局部变量
function test(){
var a = 100
function test2(){
console.log(a)
}
return test2
}
test()()//100
2,让局部变量始终生存在内存当中,避免被垃圾回收机制回收
function fun(){
var num = 1000
nAdd = function(){num+=1}
return function(){
console.log(num)
}
}
var result = fun()
result()//1000
nAdd()//1001
result()//1001
3,关注点:闭包中的this,大部分指向的都是window
var theName = 'outside'
var testObj = {
theName:'inside',
getNameFun:function(){
return function(){
console.log(this.theName)
}
}
}
testObj.getNameFun()()//outside
但是由于箭头函数的this指向是跟着父级走的,那么
var theName = 'outside'
var testObj = {
theName:'inside',
getNameFun:function(){
return ()=>{
console.log(this.theName)
}
}
}
testObj.getNameFun()()//inside
这里getNameFun的父级是testObj 这个对象,这里的this指向对象内部,打印结果为inside
网友评论