2020-06-08
1107
#vanilla javascript
Gbolahan Olagunju
19958
Jun 8, 2020 â‹… 3 min read

How to decide between classes v. closures in JavaScript

Gbolahan Olagunju Let's have a chat about your project. Find me on Twitter @iamgbols.

Recent posts:

Decoupling Monoliths Into Microservices With Feature Flags

Decoupling monoliths into microservices with feature flags

Explore how to effectively break down a monolithic application into microservices using feature flags and Flagsmith.

Kayode Adeniyi
Jul 25, 2024 â‹… 10 min read
Lots of multi-colored blue and purplish rectangles.

Animating dialog and popover elements with CSS @starting-style

Native dialog and popover elements have their own well-defined roles in modern-day frontend web development. Dialog elements are known to […]

Rahul Chhodde
Jul 24, 2024 â‹… 10 min read
Using Llama Index To Add Personal Data To Large Language Models

Using LlamaIndex to add personal data to LLMs

LlamaIndex provides tools for ingesting, processing, and implementing complex query workflows that combine data access with LLM prompting.

Ukeje Goodness
Jul 23, 2024 â‹… 5 min read
JavaScript logo on top of violet background

Exploring essential DOM methods for frontend development

Learn four groups of DOM methods and their uses to create responsive and dynamic webpages. A helpful DOM reference table is also included.

Chimezie Innocent
Jul 23, 2024 â‹… 12 min read
View all posts

3 Replies to "How to decide between classes v. closures in JavaScript"

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

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

Leave a Reply