
Learn how TanStack DB transactions ensure data consistency on the frontend with atomic updates, rollbacks, and optimistic UI in a simple order manager app.

useEffect mistakesDiscover what’s new in The Replay, LogRocket’s newsletter for dev and engineering leaders, in the November 5th issue.

useEffect mistakes to avoid in your React appsShruti Kapoor breaks down the confusion around useEffect and goes over 15 common mistakes she’s seen in the React apps she’s reviewed.

MCP is the bridge between AI and the open web — giving intelligent agents the ability to act, not just talk. Here’s how this open protocol transforms development, business models, and the future of software itself.
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.