Javascript可选,如果构造函数中有其他内容

Javascript可选,如果构造函数中有其他内容,javascript,Javascript,下面是开始的代码 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.w

下面是开始的代码

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

所以我试图在构造函数中创建一个可选属性。但是,无论我在child参数中输入什么,打印出来时它都会显示“default”。我对JS非常陌生,刚接触php。不知道为什么这不起作用。我已经研究了其他问题,试图跟进,但我从中尝试的似乎没有帮助。

为什么不使用
child=child | | |默认值“
而不是if-else语句


这实现了同样的效果。

正确的代码如下:

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
解释是,您总是将
this.child
undefined
进行比较,但您需要的是测试参数
child
,而不是
this.child

可以提供快捷方式,而不是使用
if/else

this.child = child || 'default';  

this.child
始终未定义,因为您没有定义它(您只定义了
this.name
this.age
)。顺便说一句,您应该使用
==
未定义的
进行比较。您只需要检查
子项
如果(子项==未定义){
。噢,该死。我去掉了最初的定义,我想我之前遇到的问题是我定义了两次。谢谢!谢谢你的===提示。@RussellKitchen:
child
是参数(变量).this.child
是一个属性。否,
this.child
是实例的一个属性,在定义它之前,它总是
未定义的。如果选中,您只在稍后的内部定义它。