作用域问题的理解
作者:互联网
例1:
var a = 1
function fn1(){
function fn2(){
console.log(a)
}
function fn3(){
var a = 4
fn2()
}
var a = 2
return fn3
}
var fn = fn1()
fn() //输出多少
调用过程:调用fn()=>fn1(),fn1()返回fn3,调用fn3,fn3中调用了fn2,输出2。
分析:fn2中没有a变量,fn2被定义在fn1中,获得fn1中的变量a=2
例2:
var a = 1
function fn1(){
function fn3(){
var a = 4
fn2()
}
var a = 2
return fn3
}
function fn2(){
console.log(a)
}
var fn = fn1()
fn() //输出多少
调用过程:fn()=>fn1()=>fn3()=>fn2()=>consolo.log(a)=>输出
分析:fn2中没有a变量,在fn1作用域中寻找,任没有,在全局作用域寻找,输出1
例3:var a = 1
function fn1(){
function fn3(){
function fn2(){
console.log(a)
}
var a
fn2()
a = 4
}
var a = 2
return fn3
}
var fn = fn1()
fn() //输出多少
调用过程:fn()=>fn1()=>fn3()=>fn2()=>console.log(a)=>输出undefined
分析: fn2内部没有a变量,fn3中寻找,var a已经定义,但未赋值,所以输出undefined
总结:作用域链不难,先找局部变量,再往定义该函数的作用域寻找变量,直到全局作用域即可。
==============================================================================================
if中的表达式一定要用==或者!=。单用一个=,一定会出错
==========================================================================================
标签:fn3,fn2,fn1,作用域,问题,理解,var,fn 来源: https://www.cnblogs.com/hy96/p/11368892.html