JavaScript Closures as Lightweight Objects

Did you know JavaScript can behave like Java? Not really — but it can fake it beautifully. Here's something I love about JavaScript that most beginners overlook: closures. Look at this pattern Instead of a class with private fields, we use a factory function that returns methods just like a Java object would expose getters and setters. getName() — returns the name getAge() — returns the age incrementAge() — mutates internal state What makes this powerful? The variables personName, personAge, and personJob are completely private. They can't be accessed directly from outside the function. You MUST go through the returned methods. This is a closure — the inner functions "close over" the outer scope and remember it even after the factory function has finished running. So when you call: person.incrementAge() person.getAge() you get 124. Because that personAge variable is alive, encapsulated, and mutable — all without a single class keyword. Java devs: does this feel familiar? It should. JavaScript doesn't need classes to give you encapsulation. Closures have always been there doing the heavy lifting. This is a great pattern when you want lightweight objects without the overhead of a full class definition. Drop a if this gave you a new way to think about JavaScript! #JavaScript #WebDevelopment #Programming #100DaysOfCode #SoftwareEngineering #JSClosures

  • text

To view or add a comment, sign in

Explore content categories