简体   繁体   English

为什么在我的JavaScript中无法为参数设置默认值?

[英]Why is setting default value for parameter not working in my javascript?

I want to set a default of 'small' if no options object is passed into my constructor: 如果没有选项对象传递到构造函数中,我想设置默认值“小”:

var Plan = function(options){
  this.name = options.name || 'small';
}

but when I do this: 但是当我这样做时:

var smallPlan = new Plan();

console.log(smallPlan.name);

I get Uncaught TypeError: Cannot read property 'name' of undefined 我收到Uncaught TypeError: Cannot read property 'name' of undefined

What am I doing wrong? 我究竟做错了什么? Isn't this the idiomatic way to set default parameter values in javascript? 这不是在javascript中设置默认参数值的惯用方式吗?

Instead of over complicating the code to check if options and name is there, check to see if the object is defined, if not, set it to an empty object. 与其检查代码是否繁琐而不是检查代码和名称是否复杂,不如查看是否定义了对象,如果没有,请将其设置为空对象。

var Plan = function(options){
  options = options || {};
  this.name = options.name || 'small';
}

options is undefined. options未定义。 You can't access options.name if options doesn't exist. 如果options不存在,则无法访问options.name

If you want to check for more than just one property, I'd suggest something like this: 如果您要检查的不只是一个属性,我建议使用以下方法:

var Plan = function(options){
    // Set defaults
    this.name = 'foo';
    this.title = 'bar';
    this.something = 'even more stuff';
    if(options){ // If options exists, override defaults
       this.name = options.name || this.name;
       this.title = options.title || this.title;
       this.something = options.something || this.something;
    }
}

Otherwise, I'd try this: 否则,我会尝试这样做:

var Plan = function(options){
    this.name = options ? options.name || 'small' : `small`;
}

It's a little ugly, but you'll have to check if options exists, and if options has a name property. 这有点丑陋,但是您必须检查options存在,以及options是否具有name属性。

What this does is: 这是什么:

if(options){
    if(options.name){
        this.name = options.name;
    } else {
        this.name = 'small';
    }
} else {
    this.name = 'small';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM