在JavaScript中动态选择对象的方法

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']()

翻译自: https://flaviocopes.com/javascript-dynamic-method/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值