
Learn how React Router’s Middleware API fixes leaky redirects and redundant data fetching in protected routes.

A developer’s retrospective on creating an AI video transcription agent with Mastra, an open-source TypeScript framework for building AI agents.

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.
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.