Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3
Okay I had to google what you are talking about. Interesting technique! I would assume that the performance hit is negligible. Even if you create billions of instances, the WeakMap would use negligible memory, and WeakMap access is probably O(1), so I don't think this would ever lead to problems. That being said it's a hack, and I'm not sure it's necessary! Private properties are only a crutch for the programmer--as long as we all agree that underscore-prefixed means "private" we don't need to worry about it and can go back to programming. We don't need workarounds to enforce it, because who are you hiding these props from, yourself? Browser support for private props is decent, you can always use babeljs to make it work everywhere. I prefer typescript myself because there, the "private" modifier is enforced at compile-time. Though of course if you are running babeled javascript, then that's probably worse than WeakMap, performance-wise.
3rd Feb 2022, 11:02 PM
Schindlabua
Schindlabua - avatar
+ 2
Not sure I understand the question correctly. What are you proposing to do with WeakMap? You can declare private fields in Javascript, like so: class ClassWithPrivateField { #privateField; } https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Private_class_fields Haven't really used the feature myself yet though. I doubt there are any performance penalties when using private fields and methods.
3rd Feb 2022, 10:30 PM
Schindlabua
Schindlabua - avatar