Search code examples
javascriptoopdefault-value

Setting default values for properties in Javascript


How can I set default values for the properties p1,p2,p3 and p4` of a class:

class O extends AnotherClass {

    constructor(p1,p2,p3,p4) {
    super(); \\ for the this-reference
    if (p1) this.p1 = p1;
    if (p2) this.p2 = p2;
    if (p3) this.p3 = p3;
    if (p4) this.p3 = p4;

    }

do I have to write one by one

O.prototype.p1 = "default1"
O.prototype.p2 = "default2"
O.prototype.p3 = "default3"
O.prototype.p4 = "default4"

or is there a more elegant way, like

O.prototype = {p1: "default1", p2 : "default1", p3 : "default3", p4 : "default4"}

but the latter does not seem to work...


Solution

  • You can set default properties in es6 when you declare params in your constructor like this constructor(p1 = 'Default Variable',p2 = 'Default Variable',p3 = 'Default Variable',p4 = 'Default Variable')