Matthew Harwood Matthew Harwood - 13 days ago 6
Javascript Question

Is it possible in es6 to instantiate a class and define prototype properties similar to a classical constructor?

In ES6 when you create a class with prototype properties how can I set those props

baz
and
biz
on instantiation (
new
) of class?

class Foo {}

Foo.prototype.baz = 1;
Foo.prototype.biz = 'wow';

var thing = new Foo() // How to also set prototype values of .baz & .biz on creation?



class Baz {

constructor(biz) {
this.biz = biz
}
}

var baz = new Baz(); // will not put properties on the prototype.

Answer

It is

class Baz {
  constructor(biz) {
    Object.getPrototypeOf(this).biz = biz
  }
}

const baz1 = new Baz(1); // baz1.biz === 1
const baz2 = new Baz(2); // baz2.biz === 2
baz1.biz === baz2.biz; // === 2

And it is not something the one would want to do in any reasonable scenario.

Comments