模块模式是否需要使用 IIFE?
Does the module pattern require the use of an IIFE?
在 Udacity 课程中,它说了关于模块模式的矛盾内容:
The Module Pattern requires the use of IIFE's
和
At its core, the Module Pattern leverages scope, closures, and (commonly) IIFE's.
所以,如果我理解正确的话,模块模式需要使用闭包,但是闭包是否需要在 IIFE 中?
在 JavaScript ECMAScript 5 及更早版本中,an IIFE, or immediately-invoked function expression, was necessary to create a function scope that prevented var
声明在实现显示模块模式时会污染全局命名空间。
(function () {
var foo = 'bar'
var counter = 0
this.someGlobalModule = function () {
counter++
return { foo: foo, counter: counter }
}
}.call(this))
// this === window at top-level in browser
// no access to function-scope foo or counter, only someGlobalModule()
var value = someGlobalModule()
// value.foo === 'bar'
// value.counter === 1
现在使用 JavaScript ECMAScript 6,引入 const
and let
declarations allow block-scope variables, as opposed to function-scope, so you can simply use a block-scope 来实现显示模块模式:
{
const foo = 'bar'
let counter = 0
// this === window at top-level in browser
this.someGlobalModule = () => {
counter++
return { foo, counter }
}
}
// no access to block-scope foo or counter, only someGlobalModule()
let value = someGlobalModule()
// value.foo === 'bar'
// value.counter === 1
在 Udacity 课程中,它说了关于模块模式的矛盾内容:
The Module Pattern requires the use of IIFE's
和
At its core, the Module Pattern leverages scope, closures, and (commonly) IIFE's.
所以,如果我理解正确的话,模块模式需要使用闭包,但是闭包是否需要在 IIFE 中?
在 JavaScript ECMAScript 5 及更早版本中,an IIFE, or immediately-invoked function expression, was necessary to create a function scope that prevented var
声明在实现显示模块模式时会污染全局命名空间。
(function () {
var foo = 'bar'
var counter = 0
this.someGlobalModule = function () {
counter++
return { foo: foo, counter: counter }
}
}.call(this))
// this === window at top-level in browser
// no access to function-scope foo or counter, only someGlobalModule()
var value = someGlobalModule()
// value.foo === 'bar'
// value.counter === 1
现在使用 JavaScript ECMAScript 6,引入 const
and let
declarations allow block-scope variables, as opposed to function-scope, so you can simply use a block-scope 来实现显示模块模式:
{
const foo = 'bar'
let counter = 0
// this === window at top-level in browser
this.someGlobalModule = () => {
counter++
return { foo, counter }
}
}
// no access to block-scope foo or counter, only someGlobalModule()
let value = someGlobalModule()
// value.foo === 'bar'
// value.counter === 1