Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What’s the difference between using objects and functions for namespacing in Javascript?

Tags:

javascript

I saw these 2 basic ways of namespacing in JavaScript.

  1. Using object:

    var Namespace = { };

    Namespace.Class1 = function() { ... };

  2. Using function:

    function Namespace() { };

    Namespace.Class1 = function() { ... };

How do they differ? Thank you.


2 Answers

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

These properties do not intersect with Object so the object-as-namespace approach will not have these behaviours.

like image 104
JPot Avatar answered Sep 13 '25 19:09

JPot


The first one declares a simple object while the second one declares a function. In JavaScript, functions are also objects, so there is almost no difference between the two except that in the second example you can call Namespace() as a function.

like image 39
casablanca Avatar answered Sep 13 '25 18:09

casablanca