[英]How can I define a static method in JavaScript to use with or without parenthesis?
我有下面定义的 ES6 车辆 class。 我想要一个 static 方法,这样我就可以在有或没有括号的情况下使用。 我已经定义static AvailableTypes
和static 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.