What would a Immediately Invoked Class Expression in JavaScript look like. This is the question I asked myself. I couldnt find anything online, so I created one.
Below we have a Immediately Invoked Class Expression. This could also be called a Self-Executing Anonymous Class.
void new class {
constructor () {
console.log("hello world")
}
}
We have all heard of the Immediately Invoked Function Expression (IIFE) it is also known as a Self-Executing Anonymous Function. I was curious how this would look with Classes. There are two parts of a IIFE.
A IIFE is a design pattern which is also known as a Self-Executing Anonymous Function and contains two major parts. The first is the anonymous function with lexical scope enclosed within the Grouping Operator (). This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
The second part creates the immediately executing function expression () through which the JavaScript engine will directly interpret the function.
(function () {
console.log("hello world")
})();
To replicate this, our IICE would need at least these two features.
void new class {
constructor () {
console.log('MyClass');
this.method()
}
method () {
console.log('MyClass method');
}
}
Above is what a IICE looks like. There are a few parts to this design pattern. Let me take you through them.
The void
operator evaluates the given expression and then returns undefined
. This will prevent our class polluting the global scope by always returning undefined
.
The new
operator interprets the defined anonymous class immediatly. This then calls the classes constructor
function as per the ECMAscript spec.
So there we have it. A working, valid immediately invoked class expression (IICE).
Is this actually something or an idea??