Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TS/ES6: Instantiate class without calling constructor

Is there any way how to instantiate new class instance without calling its constructor?

Something like this:

class Test {
    constructor(foo) {
        this.foo = 'test';
    }
}

const a = new Test('bar'); // call constructor
const b = Test.create();   // do not call constructor
console.log(a.foo, a instanceof Test); // bar, true
console.log(b.foo, b instanceof Test); // undefined, true

I am trying to develop TS mongo ORM, and would like to use constructors of entities for creating new objects, but do not want to call them when instancing entities of already persisted objects (those that are already stored in DB).

I know that doctrine (PHP ORM) uses this approach, but afaik they are using proxy classes to achieve it. Is there any easy way to achieve this in typescript (or generally in ES6/ES7)?

I already found this question ES6: call class constructor without new keyword, that asks for the opposite, and saw one answer mentioning Proxy object. That sounds like a possible way to go, but from the docs I am not really sure if it is achievable.

like image 273
Martin Adámek Avatar asked Dec 11 '22 06:12

Martin Adámek


1 Answers

You can add a static method create, that create an Object from the class prototype. Something like that should work:

class Test {
  constructor(foo) {
    this.foo = foo
  }
  static create() {
    return Object.create(this.prototype)
  }
}

const a = new Test('bar') // call constructor
const b = Test.create()   // do not call constructor
console.log(a.foo, a instanceof Test) // bar, true
console.log(b.foo, b instanceof Test) // undefined, true
like image 91
ZER0 Avatar answered Dec 12 '22 19:12

ZER0