Intro
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 */; // (#)
ES6 constructorless function (class)
class _Static {
constructor() {
return new {}(); // (#) : {} is not a constructor if new'ed
}
static _constructor() {
let _this = {};
_this.namespace = _Static.name;
_this.otherProps = "xyz";
return _this;
}
// other static methods
}
_Static._constructor(); // {namespace: '_Static', otherProps: 'xyz'}
/* new _Static(); */ // (#)
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 */);
BONUS for 2 ed.
// Why this way i.e. first parameter as null :
Math.max.call(null/*, comma seperated params (if any) */)
// But not that way :
Math.max.call(this/*, 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)
Related articles
- Prototypless namespaces in JavaScript
- Static vs. Singleton in JavaScript
- 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)