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.

Top comments (1)

Collapse
 
mohsenbazmi profile image
Mohsen Bazmi • Edited

Interesting

typescript

11 Tips That Make You a Better Typescript Programmer

1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields

...

Read the whole post now!

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay