为什么将javascript名称空间作为函数? [英] Why base a javascript namespace as a function?
问题描述
我正在阅读一个库的源代码,该库必须保持匿名,并且我看到它正在使用一个空函数来设置名称空间.它似乎与对象文字符号(OLN)相似,只是基数是一个函数.
I was reading the source code of a library, which must remain anonymous, and I see that it's using an empty function to setup the namespace. It appears to be similar to the object literal notation (OLN) except that the base is a function.
这是声明的示例.
/**
* Base namespace for FOO library
* @name FOO
* @namespace
*/
function FOO(){}
FOO.bar = 'bar const..';
FOO.fooFunc = function () { /* code */ };
FOO.Bar = function () { /* some constructor */ };
FOO.Bar.prototype.baz = function () { /* A prototype method on FOO.Bar */ };
...
如您所见,FOO名称空间是一个空函数.是否有必要将命名空间声明为空函数?这是对OLN模式的滥用吗?看来这可能是工厂模式的开始.名称空间上没有原型方法(例如FOO.prototype.bar = ...
).显然,调用FOO()
不会执行任何操作.有人认出这种模式吗?
As you can see, the FOO namespace is an empty function. Is there any point of declaring the namespace as an empty function? Is this a misuse of the OLN pattern? It looks like it may have been the start of a factory pattern. There's no prototype methods on the namespace (e.g. FOO.prototype.bar = ...
). Calling FOO()
clearly does nothing. Does anyone recognize this pattern?
推荐答案
命名函数为 悬挂 -有效地移至其封闭范围的顶部.使用命名函数可以允许在声明名称空间之前进行赋值:
Named functions are hoisted - effectively moved to the top of their enclosing scope. Using a named function could allow assignment before the namespace is declared:
FOO.bar = "bar";
function FOO() {}
console.log(FOO.bar); // bar
与Object文字(或未命名的函数)相比:
Compared to an Object literal (or non-named function):
FOO.bar = "bar";
var FOO = {};
console.log(FOO.bar); // undefined
任何人不太可能计划将成员分配到这样的命名空间,但这可能会发生.
It's unlikely that anybody would plan to assign members to a namespace like this, but it could happen.
我能想到的唯一另一个优点是,函数可以具有一个固有的名称,这可能对调试很有用.
The only other advantage I can think of a is that functions can have an inherent name, which may be useful for debugging.
例如,如果名称空间成员具有namespace
属性(他们可能没有):
For example, if namespace members had a namespace
property (which they probably don't):
function FOO(){}
FOO.bar = { namespace: FOO };
console.log(FOO.bar.namespace); // function FOO(){}
相比:
var FOO = {};
FOO.bar = { namespace: FOO };
console.log(FOO.bar.namespace); // Object {bar: Object}
纯粹的推测:某些名称空间也可能使用这样的函数进行初始化.这可能是一个名称空间的示例,该名称空间不需要任何初始化,但是选择使用函数来保持一致性.
Pure speculation: it's also possible that some namespaces could use a function like this for initialisation. This could be an example of a namespace that does not need any initialisation, but chooses to use a function for consistency.
这篇关于为什么将javascript名称空间作为函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!