
Kombai AI converts Figma designs into clean, responsive frontend code. It helps developers build production-ready UIs faster while keeping design accuracy and code quality intact.

Discover what’s new in The Replay, LogRocket’s newsletter for dev and engineering leaders, in the October 22nd issue.

John Reilly discusses how software development has been changed by the innovations of AI: both the positives and the negatives.

Learn how to effectively debug with Chrome DevTools MCP server, which provides AI agents access to Chrome DevTools directly inside your favorite code editor.
Hey there, want to help make our blog better?
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.