loading...

TypeScript/JavaScript Class with Closure

akashkava profile image Akash Kava ・1 min read

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

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;

}

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

Here, you cannot create a childClass without parent.

Posted on by:

Discussion

markdown guide