Sometimes you have an object and you need to call a method, or a different method, depending on some condition.
有时您有一个对象,并且需要根据某种条件调用一个方法或其他方法。
For example you have a car
object and you either want to drive()
it or to park()
it, depending on the driver.sleepy
value.
例如,您有一个car
对象,您想根据driver.sleepy
值将其drive()
或将其park()
。
If the driver has a sleepy level over 6, we need to park the car before it fells asleep while driving.
如果驾驶员的困倦程度超过6,我们需要先停放汽车,然后才能在驾驶过程中入睡。
Here is how you achieve this with an if/else
condition:
这是在if/else
条件下实现此目标的方法:
if (driver.sleepy > 6) {
car.park()
} else {
car.drive()
}
Let’s rewrite this to be more dynamic.
让我们将其重写为更具动态性。
We can use the ternary operator to dynamically choose the method name, get it as the string value.
我们可以使用三元运算符来动态选择方法名称,并将其作为字符串值。
Using square brackets we can select it from the object’s available methods:
我们可以使用方括号从对象的可用方法中选择它:
car[driver.sleepy > 6 ? 'park' : 'drive']
With the above statement we get the method reference. We can directly invoke it by appending the parentheses:
通过上面的语句,我们获得了方法参考。 我们可以通过添加括号直接调用它:
car[driver.sleepy > 6 ? 'park' : 'drive']()