0

I know it has been asked and answered how to set a default parameter for a javascript function by Tilendor

I was wondering if I had a function containing a series of booleans.
For example, a function called 'anAnimal' and as a default I set a value of false to three propertys.
fly, swim, and climb.

What would I do if I just want to pass in an argument of true to my property called climb?

Currently when calling in the method I have to pass in a value of false for fly and swim even though I have already predefined them as false.


This is what I am attempting and I would like the result to say true instead of false

function anAnimal (fly = false, swim = false, climb = false) {
    this.canFly = fly;
    this.canSwim = swim;
    this.canClimb = climb;
} 

var cat = new anAnimal(true)

var theCat = 'This cat can climb: ' + cat.canClimb;

document.write(theCat);
Mark
  • 121
  • 2
  • 12
  • You have to put all arguments in. In your example your cat can fly. (Try `cat.canFly`) - So change the cat invocation to `var cat = new Animal(false, false, true)` – evolutionxbox Mar 09 '17 at 10:27
  • 1
    Why not using setters ? `setSwim()` `setFly()` ... ? I think that's more Object Oriented – teeyo Mar 09 '17 at 10:28
  • function overloading is not possible in js. You need to create the object using all arguments. – Jijo Cleetus Mar 09 '17 at 10:28
  • 1
    A different thought, need a bit twist. Instead of expecting three parameters, you can combine three arguments in a single object - can be named as capability- and then it will be a single parameter. And while creating new Object you can create the parameter object with single property climb.. – Abhisek Malakar Mar 09 '17 at 10:32

1 Answers1

1

You can pass an object instead of arguments and populate default option based on inputs.

function anAnimal(obj) {
  var defaults = {
    fly: false,
    swim: false,
    climb: false
  }

  //copy the values of all enumerable own properties from one or more source objects to a target object.
  Object.assign(defaults, obj);

  //Assign the values
  this.canFly = defaults.fly;
  this.canSwim = defaults.swim;
  this.canClimb = defaults.climb;
}

var cat = new anAnimal({
  climb: true
});
var theCat = 'This cat can climb: ' + cat.canClimb;
document.write(theCat);

However I would recommend to use setters i.e. setClimb()

Satpal
  • 132,252
  • 13
  • 159
  • 168