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

后端 未结 4 1612

I saw these 2 basic ways of namespacing in JavaScript.

  1. Using object:

    var Namespace = { };

    Namespace.Clas

4条回答
  •  情歌与酒
    2020-12-08 11:24

    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.

提交回复
热议问题