How to set default boolean values in JavaScript?

后端 未结 5 1522
执念已碎
执念已碎 2021-01-31 01:38

Setting default optional values in JavaScript is usually done via the || character

var Car = function(color) {
  this.color = color || \'blue\';
};
         


        
5条回答
  •  清酒与你
    2021-01-31 02:05

    You can use the Default function parameters feature in ECMA6. Today, ECMA6 is still not fully supported in the browser but you can use babel and start using the new features right away.

    So, the original example will become as simple as:

    // specify default value for the hasWheels parameter
    var Car = function(hasWheels = true) {
      this.hasWheels = hasWheels;
    }
    
    var myCar = new Car();
    console.log(myCar.hasWheels); // true
    
    var myOtherCar = new Car(false)
    console.log(myOtherCar.hasWheels); // false
    

提交回复
热议问题