DEV Community

Akash Kava
Akash Kava

Posted on

2 1

TypeScript/JavaScript Class with Closure

Classes are nothing but functions, and creation of classes can be bound to a closure in an interesting way, while building I needed to attach a closure with class. And to my surprise it did work correctly.


function ClassWithClosure(parent) {
   return class ClassWith {

       constructor(x) {
          this.x = x;
       }

       compute() {
          return this.x + parent;
       }
   };
}


var ClassWith2 = ClassWithClosure(2);
var ClassWith3 = ClassWithClosure(3);

var cw2 = new ClassWith2(2);
var cw3 = new ClassWith3(2);


cw2.compute(); // 4
cw3.compute(); // 5

Enter fullscreen mode Exit fullscreen mode

Basically it works as class is simply a function constructor which is a function which can easily hold any closure.

function ClassWithClosure(parent) {

   function ClassWith(x) {
      this.x = x;
   }

   ClassWith.prototype.compute = function() {
      return this.x + parent;
   }

   return ClassWith;

}

Enter fullscreen mode Exit fullscreen mode

Note this is not same as static, static variable is constant for every new instance.

This is specifically useful when you want to create nested classes like Java which can not exist without parent.

class Parent {

    get childClass(): BaseClass {
        const parent = this;

        // wow nested class !!
        return class Child extends BaseClass {
            get parent(): Parent {
                return parent;
            }
        } 
    }

}

const p1 = new Parent();
const p2 = new Parent();

const c1 = new p1.childClass(); // of type BaseClass
const c2 = new p1.childClass(); // of type BaseClass

c1 === c2 // false;
c1.parent === c2.parent// true
Enter fullscreen mode Exit fullscreen mode

Here, you cannot create a childClass without parent.

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (1)

Collapse
 
mohsenbazmi profile image
Mohsen Bazmi • • Edited

Interesting

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay