
Check out Google’s latest AI releases, Gemini and the Antigravity AI IDE. Understand what’s new, how they work, and how they can reshape your development workflow.

Learn about Bun 1.3, which marks a shift from fast runtime to full JS toolchain—and see the impact of Anthropic’s acquisition of Bun.

Stop defaulting to JavaScript. Modern CSS handles virtualization, responsive layouts, and scroll animations better than ever – with far less code.

React’s next era, AI code review tools, and more: discover what’s new in The Replay, LogRocket’s newsletter for dev and engineering leaders, in the December 3rd issue.
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up now
3 Replies to "How to decide between classes v. closures in JavaScript"
Why aren’t you building your Closure like your class and getting the best of both worlds?
let UserClosure = function(firstName, lastName, age, occupation) {
this.firstName = params.firstName;
this.lastName = params.lastName;
this.age = age;
this.occupation = occupation;
let privateValue = “Can’t see this!”;
function privateFunction(args) { // private method }
}
UserClosure.prototype.getAge = function() { return this.age; }
UserClosure.prototype.describeSelf = function() { …. };
let someOne = new UserClose(“first”, “last”, 55, “dev”);
This isn’t intended as argumentative. I’m looking for why I should start using classes instead of the above construction in some upcoming work.
This is not a closure but a constructor function. You have it all mixed up badly :/
Here’s how to get the best of both worlds.
const Foo = (function() {
//create a prototype.
const prot = {
bar(bas) {
bas = bas || this.fallbackBas;
console.log(“bar says ” + bas);
}
} //end of prot.
//constructor.
return function(fallback) {
const o = Object.create(prot);
//new object, prot as prototype.
o.fallbackBas = fallback;
return o;
} //constructor
})(); //iif
const f = new Foo(“This is a fallback.”);
f.bar(“This is not a fallback.”);
f.bar();
/*Output:
bar says This is not a fallback.
bar says This is a fallback.
*/
All the funcs are created only once, and other vars can go in the same outer func.