Function scope and closure

Body and the closure is a function of context

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

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

Typically, there will be an internal closure "free variable", the variable is outside the scope of the definition, when the external scope variable value changes, "free variable" within the closure will change accordingly.

Therefore, the closure body is a function of the context and, often referred to as "open function", because the value of "free variable" depends in part on the results of actual operation runtime.

Under the scope of the function closure

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

However, note that the "free variable" is defined scope. If the "free variables" is defined in the function scope, then the same function is called many times more than the return of closures carried by them independent of context.

This is because the Javascript function scope is isolated from each other, so the reference to "free variables" are also isolated from each other.

Guess you like

Origin www.cnblogs.com/Peter2014/p/12096217.html