繁体   English   中英

如何在 JavaScript 中定义一个 static 方法来使用或不使用括号?

[英]How can I define a static method in JavaScript to use with or without parenthesis?

我有下面定义的 ES6 车辆 class。 我想要一个 static 方法,这样我就可以在有或没有括号的情况下使用。 我已经定义static AvailableTypesstatic AvailableTypes()但它给出了一个错误TypeError: Vehicle.AvailableTypes is not a function


class Vehicle {
  constructor({ vehicleType = 'car', name = '', range = '', seats = '' }) {
    this.vehicleType = vehicleType
    this.name = name
    this.range = range
    this.seats = seats
  }

  getRangeToSeatsRatio() {
    return this.range / this.seats
  }

  get rangeToSeatsRatio() {
    return this.range / this.seats
  }

  static AvailableTypes = ['car', 'plane']
  static  AvailableTypes() {
    return this.AvailableTypes
  }
}

const vehicle = new Vehicle({ name: 'My Car name', seats: 500, wheels: 45 })
console.log(Vehicle.AvailableTypes) // (2) ['car', 'plane']
console.log(Vehicle.AvailableTypes()) //TypeError: Vehicle.AvailableTypes is not a function

这应该导致availableVehicleTypes['car', 'plane']

const availableVehicleTypes = Vehicle.AvailableTypes;

这也应该导致availableVehicleTypes['car', 'plane']

const availableVehicleTypes = Vehicle.AvailableTypes();

不可能创建一个既是 function 又是数组的值。

下定决心,只在两者中选择一个,这样你的 class 的用户就不会那么困惑了。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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