函数作用域和闭包

闭包是函数和上下文环境的合体

const a = {}
let type = 'directive'
a[type] = function () {
    console.log(type)
}
type = 'component'

// 在运行的时刻,type的值为'component'
a.directive() // component
a.directive() // component

通常,闭包内部会存在一个“自由变量”,这个变量是在外部作用域定义的,当外部作用域的变量值发生变化,闭包内的“自由变量”也就相应变化。

所以,闭包是函数和上下文环境的合体,通常也称之为“开放函数”,因为实际运行结果部分取决于运行时“自由变量”的取值。

函数作用域下的闭包

const a = {}
const assets = ['directive', 'component']
assets.forEach((type) => {
    a[type] = function () {
        console.log(type)
    }
})
a.directive() // directive 这里为什么不是 component ?
a.component() // component

但是,要注意“自由变量”的定义作用域。如果“自由变量”定义在函数作用域内,那么同一个函数被多次调用所返回的多个闭包他们所携带的上下文环境相互独立。

这是因为在Javascript中函数作用域是互相隔绝的,所以“自由变量”的引用也是互相隔绝的。

猜你喜欢

转载自www.cnblogs.com/Peter2014/p/12096217.html