简体   繁体   中英

Bypass a set parameter when calling a JavaScript method?

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

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 ie setClimb()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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