Reputation: 18781
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.
Upvotes: 1
Views: 214
Reputation: 222493
It is
class Baz {
constructor(biz) {
Object.getPrototypeOf(this).biz = biz
// or
// this.constructor.prototype.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.
Upvotes: 2
Reputation: 664538
Yes, you can set prototype properties just like that, just like we did without using class
syntax.
How to also set prototype value on creation?
You cannot. Prototypes have nothing to do with instantiation. If you want instance properties, put them in the constructor, but they won't be prototype properties any more. If you want inherited properties, put them on the prototype, but they're shared between all instances and not created with every object.
Upvotes: 1