1

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...

3
  • 2
    this.p1 = p1 || 'some default value', etc Commented Mar 14, 2017 at 22:20
  • Why do you not pass parameters to super()? Commented Mar 14, 2017 at 22:35
  • 1
    Note that if (p1) will evaluate to false for values other than undefined, such as null, 0, false, etc. You might be better off with a typeof test. Commented Mar 14, 2017 at 22:39

3 Answers 3

5

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')

Sign up to request clarification or add additional context in comments.

Comments

1

In addition to plain ES2015+ default parameter values as @Fried_Chicken has already answered, there's still an alternate approach.

Why don't you accept arguments as an object and then, you use ES2015+ destructuring capabilities? This is a great choice as you can provide the whole arguments in any order, or even provide just one or some of them.

Also, you won't need to provide null/undefined to some given parameters:

doStuff(1, null, null, 2); 

See the following runnable code snippet and play with it. The same solution can be applied in your scenario as destructuring can be used on class constructors.

function doStuff({ arg0 = null, arg1 = null } = {}) {
  if (arg0 !== null) {
      console.log(arg0);
  } else {
      console.log("not provided");
  }
}

doStuff();
doStuff({ arg0: "hello world" });

2 Comments

Whoa, since when does StackOverflow have runnable code snippets?
@MichaelHewson Hey, I'm not sure about that, but I believe it was more than a year ago!
0
  constructor(p1, p2, p3, p4) {
    super();
    if (p1) this.p1 = p1 === undefined ? "p1Default" : p1;
    if (p2) this.p2 = p2 === undefined ? "p2Default" : p2;
    if (p3) this.p3 = p3 === undefined ? "p3Default" : p3;
    if (p4) this.p3 = p4 === undefined ? "p4Default" : p4;
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.