4 ms·
Factory functions don't mean using the (admittedly ugly) IIFE syntax or accessing __proto__ fields. This is an example of factory function function NewObj(
by SPBS 5y ago
Factory functions don't mean using the (admittedly ugly) IIFE syntax or accessing __proto__ fields. This is an example of factory function
function NewObj(n) {
let myPublicInt = n;
let myPrivateInt = 0;
function privateIncrement() { myPrivateInt++; }
function incrementPrivateInt() { privateIncrement(); }
function printPrivateInt() { console.log(myPrivateInt); }
return {
myPublicInt,
incrementPrivateInt,
printPrivateInt,
};
}
let obj = NewObj(5);
console.log(obj.myPublicInt); // 5, because myPublicInt is a public field
console.log(obj.myPrivateInt); // undefined, because myPrivateInt is a private field
// obj.privateIncrement(); // exception, because privateIncrement is a private method
obj.printPrivateInt(); // 0
obj.incrementPrivateInt();
obj.printPrivateInt(); // 1
- tehbeard 5y agoso..... how do you know to optimize this as a factory function / "class" in your JS runtime with reusable instructions that just use an instance's scope in order to get good performance and memory usage.... When all that's being spat out is a JS object, that the user could very well modify in the next instruction, 30 instructions time, or conditionally based on some other checks? And it's still a pretty ugly way of defining a class like object without the syntactics.
- hinoki 5y agoBut an object constructed from a class still has all the optimisation problems you just mentioned. It’s just syntactic sugar. The optimiser generates invariants which, if invalidated, makes you fall back to a slow path.
- tehbeard 5y agoThe syntactic sugar is something the optimiser is aware of and isn't just a "do this in a more pretty/stylised way" for the developer, it conveys an intent that this is a construct that can be optimized with a certain level of confidence that you can't get from objects that "look like a duck and quack like a duck" if you squint a little. And if anything happens that does "deoptimize" it, then if we know the "base" is definitely a class, the paths to handle the "deoptimization" can make better decisions and be able to avoid scrapping everything and falling back to the slow path.
- felixfbecker 5y agoJavaScript engines like V8 can already do exactly as you said through hidden classes based on source code position and have been doing so for a long time. I haven't read any evidence that classes are actually better optimized, even if it's often argued as the reason for why classes are better.