DEV Community

LG
LG

Posted on • Edited on

4 3

Prototypeless namespaces examples in JS | 2 ed.

Revising prototype-based inheritance in JS discovered a worth mentioned way of defining , some may say "overhead", prototypeless namespaces in global & local scopes , i.e.:

// global namespace :
global_namespace = Object.create(null)
global_namespace['namespace_name'] = "global_namespace"; 
console.log(global_namespace) // {namespace_name: 'global_namespace'}

// local namespace :
(function (){
    // TIP # classically we could use function-scoped var instead of let, but ***"let"*** it be :
    let local_namespace = Object.create(null);
    local_namespace['namespace_name'] = "local_namespace"
    return [local_namespace, global_namespace];
}())
/** Console output :
(2) [{…}, {…}]
0: {namespace_name: 'local_namespace'}
1: {namespace_name: 'global_namespace'} # NOTE : global accessible through n-th tuple nesting
length: 2
[[Prototype]]: Array(0)
*/

local_namespace // local_namespace is not defined at <anonymous> # just as expected
Enter fullscreen mode Exit fullscreen mode

Since ed. 2 :

Prototypeless also means constructorless a.k.a singleton, but not vice versa i.e. constructorless can be prototype-based in JS land :

let obj = Object.create(null) // prototypeless object
/* obj.propKey = propValue; */// prototypeless also means constructorless, resulting in the term of "singleton"
let isInstance = new obj
console.log(isInstance) // TypeError: obj is not a constructor – that's what you suppose to expect
// ===
// NOTE : constructorless can be prototype-based, but not vise versa with regards to example shown above !
// For more read about : @https://dev.to/projektorius96/constructorless-namespaces-in-es5-es6-14pk

Related articles

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more