简体   繁体   中英

Can I conditionally pass a property into an object?

Is it possible to conditionally pass a property into an object-based function:

myFunction
      .x()
      .y()
      .x();

Here, I'd like to only pass in y() based on a condition, something like:

myFunction
      .x()
      [isTrue && y()]
      .x();

Any help much appreciated, thanks

You could use that syntax if you wanted to choose between different methods dynamically. But there's no "do nothing" method that you can substitute in place of y when the condition is false.

Use an if statement instead.

let temp = myFunction.x();
if (isTrue) {
    temp = temp.y();
}
temp.x()

Here's another solution that is more like what you originally imagined. Barmar's solution will work just fine, but I thought I'd show a different approach more like you imagined:

obj
  .x()
  [doIt ? "y" : "noop"]()
  .x();

In this scheme, doIt is any boolean or boolean expression and .noop() is a "do nothing" method on the object.

And, here's a working example you can run in a snippet:

 const obj = { x() { console.log("executing x() method"); return this; }, y() { console.log("executing y() method"); return this; }, noop() { console.log("executing noop() method"); return this; } } // try both values of the boolean for (let doIt of [true, false]) { console.log(`\nresults for doIt = ${doIt}`); obj.x() [doIt? "y": "noop"]().x(); }

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