问题描述
我在JavaScript中看到了这两种基本的命名空间方式。
I saw these 2 basic ways of namespacing in JavaScript.
-
使用对象:
Using object:
var Namespace = {};
var Namespace = { };
Namespace.Class1 = function(){...};
使用函数:
function命名空间(){};
function Namespace() { };
Namespace.Class1 = function(){...};
他们有何不同?谢谢。
推荐答案
正如其他人所指出的,函数是一个对象,因此这两种形式可以互换。作为旁注,jQuery使用函数作为命名空间的方法来支持调用和命名空间(如果你想知道还有谁做那种事或为什么)。
As others have pointed out, a function is an object so the two forms can be interchangeable. As a side note, jQuery utilizes the function-as-namespace approach in order to support invocation and namespacing (in case you're wondering who else does that sort of thing or why).
然而,使用函数名称空间方法,有一些保留属性不应该被触及或者是不可变的:
However with the function-as-namespace approach, there are reserved properties that should not be touched or are otherwise immutable:
function Namespace(){}
Namespace.name = "foo"; // does nothing, "name" is immutable
Namespace.length = 3; // does nothing, "length" is immutable
Namespace.caller = "me"; // does nothing, "caller" is immutable
Namespace.call = "1-800-555-5555" // prob not a good idea, because...
// some user of your library tries to invoke the
// standard "call()" method available on functions...
Namespace.call(this, arg); // Boom, TypeError
这些属性与 Object $不相交c $ c>所以object-as-namespace方法不会有这些行为。
These properties do not intersect with Object
so the object-as-namespace approach will not have these behaviours.
这篇关于在Javascript中使用命名空间的对象和函数有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!