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)

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay