IIFE in ES6 class literal
No, not yet at least. ES6 classes only have support for declaring methods, so anything that's not directly a method (this includes things that indirectly evaluate to a method, such as IIFE) must still be declared with the prototype.
However, ES6 classes really work the same as ES5 constructor functions do, only with a bit cleaner syntax, so you can still do this:
class MyClass {
constructor() {
/* initialize */
}
regularMethod() {
/* some stuff */
}
}
MyClass.prototype.myMethod = (function() { return function() })()
which would be equivalent to this:
function MyClass() {
/* initialize */
}
MyClass.prototype.regularMethod = function() {
/* some stuff */
}
MyClass.prototype.myMethod = (function() { return function() })()
2019 UPDATE
YES, you can do it.
You just need to create the IIFE like a "function expression" (assign it to a variable)
class MyClass {
IIFE = (() => {
let textArrayCreatedJustOnce = ['text A', 'text B', 'text C'];
console.log('Only called in object creation');
return () => {
console.log(textArrayCreatedJustOnce[1]);
}
})()
}
let myClassInstance = new MyClass(); //log: 'Only called in object creation'
myClassInstance.IIFE(); //log: 'text B'
myClassInstance.IIFE(); //log: 'text B'
myClassInstance.IIFE(); //log: 'text B'
It's possible to crate a decorator:
function iife(target, key, { value: fn, configurable, enumerable }) {
return {
configurable,
enumerable,
value: fn(),
};
}
And use it like:
class MyClass {
@iife
methodName() {
/* some stuff */
return function() {
/* real method content */
}
}
}
I use it if I need some heavy temporary variables like matrices of vectors that I don't want to crate for each method call.