Having class inside an object

Viewed 60

I need to have a class inside an object, to be used with dot notation. Is it possible?

Are there any other ways to achieve the same result?

Example:

const Obj {
  
  info(i) { console.log(i); },
  
  class Num {
  
    constructor(n) {
      this.n = n || 5;
    }
    run() {
      console.log(this.n);
    }
  }
}

const n = new Obj.Num();
2 Answers

Yeah it's strange but possible.

const Obj = {
  info(i) { console.log(i); },
}


class Num {

  constructor(n) {
    this.n = n || 5;
  }
  run() {
    console.log(this.n);
  }
}

Obj.Num = Num;

const n = new Obj.Num();
console.log(n);

Yes, just set a key for it

const Obj = {
  info(i) { console.log(i); },
  Num: class { // or Num: Class Num

    constructor(n) {
      this.n = n || 5;
    }
    run() {
      console.log(this.n);
    }
  }
}


const n = new Obj.Num();
console.log(n);

Related