DEV Community

Lukas Gaucas
Lukas Gaucas

Posted on • Updated on

Constructorless namespaces in ES5 & ES6 | 2.1 ed.


If you remove constructor from function such function becomes "sterilized" i.e. it becomes object literal subsequently aliased as namespace , although definition of "namespace" is not baked-in JavaScript (ECMAScript) specification natively . As ESnext evolving rapidly, well since last ES5 to ES6 for major update around 6 years ago, that time function definition syntactically was switched into definition of class , although this is just the way to mock real life class-based programming langs like JAVA . Don't get me wrong , I am not going into specificity , just one two show to common scenarios how to "sterilize" ES5 function / ES6 function (class syntactically) making it into nothing else than namespace...

ES5 constructorless function :

const _Static = (function () {
  /* blank : (#) _Static is not a constructor if new'ed */
}.prototype.constructor = {
  /* blank is overwritten with some mocked logic e.g. : */ _this: "local_scope",
  _getter: function () {
    return `Hello from STATIC ${this._this}`;
_Static._getter() // 'Hello from STATIC local_scope'
/* new _Static */; // (#)
Enter fullscreen mode Exit fullscreen mode

ES6 constructorless function (class)

class _Static {
  constructor() {
    return new {}(); // (#) : {} is not a constructor if new'ed

  static _constructor() {
    let _this = {};
    _this.namespace =;
    _this.otherProps = "xyz";
    return _this;

  // other static methods

_Static._constructor(); // {namespace: '_Static', otherProps: 'xyz'}

/* new _Static(); */ // (#)
Enter fullscreen mode Exit fullscreen mode

BONUS : direct way of making namespace:

You probably noticed , if you used some 2D libs like Konva.js , which uses the following signature whilst initializing things i.e. as _GlobalNamespace.Method() e.g.:

const _Konva = {
  Stage: function(){
    // Stage configs...

// new instance of Stage accessed within signature of _GlobalNamespace.Method() :
new _Konva.Stage(/* stage configs you pass as documented */);
Enter fullscreen mode Exit fullscreen mode

BONUS for 2 ed.

// Why this way i.e. first parameter as null :*, comma seperated params (if any) */)
// But not that way :*, comma seperated params (if any) */)
// Because Math is not a function constructor, you can double check with typeof Math which would give an 'object', rather than 'function' , consequently no construction, no keyword THIS exploited (upper case just for emphasis) 
Enter fullscreen mode Exit fullscreen mode

Related articles

  1. Prototypless namespaces in JavaScript
  2. Static vs. Singleton in JavaScript
  3. Visibility modifiers, keyword of static – all in one of JavaScript ES5 standard you need for today

Have anything to add , please leave a comment in the comment section below . See you in the next one !

Top comments (0)