4

Here's the code to start with.

function person(name, age, child){
    this.name = name;
    this.age = age;
    if(this.child == undefined){
        this.child = 'default';
    }else{
        this.child = child;
    }
}
var sarah = new person('sarah',34,true);

document.write(sarah.child+' ');

So I'm trying to make an optional property inside a constructor function. But whatever I put inside the child parameter it always says 'default' when printed out. I am exceedingly new to JS, just came off php. No idea why this isn't working. I've looked at other questions, tried to follow, but what I try from them doesn't seem to help.

7
  • 2
    this.child is always undefined, since you did not define it (you only defined this.name and this.age). Btw, you should use === to compare with undefined. Commented Apr 1, 2015 at 20:59
  • 2
    you just need to check child: if (child == undefined) {. Commented Apr 1, 2015 at 21:00
  • Oh damn. I took that initial definition out thinking the problem I had before was me defining it twice. Thank-you! And thankyou for the === tip. Commented Apr 1, 2015 at 21:01
  • 1
    @RussellKitchen: child is the parameter (variable). this.child is a property. Commented Apr 1, 2015 at 21:02
  • 1
    No, this.child is a property of the instance, which is always undefined before you define it. And you are only defining it later inside if check. Commented Apr 1, 2015 at 21:03

2 Answers 2

2

Why don't you just use child = child || 'default' instead of an if else statement?

This achieves the same thing.

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

Comments

0

The correct code is below:

function person(name, age, child){
    this.name = name;
    this.age = age;
    if(child == undefined){
        this.child = 'default';
    }else{
        this.child = child;
    }
}
var sarah = new person('sarah',34,true);

document.write(sarah.child+' '); // true

The explanation is that you are always comparing this.child with undefined but what you want is test the argument child instead of this.child.

A shortcut can be provided, instead of use if/else:

this.child = child || 'default';  

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.