JavaScript构造函数参数类型
我有一个表示汽车的JavaScript类,它使用两个参数构造,表示汽车的品牌和型号:JavaScript构造函数参数类型,javascript,constructor,types,Javascript,Constructor,Types,我有一个表示汽车的JavaScript类,它使用两个参数构造,表示汽车的品牌和型号: function Car(make, model) { this.getMake = function( ) { return make; } this.getModel = function( ) { return model; } } 是否有方法验证提供给构造函数的make和model是字符串?例如,我希望用户能够说 myCar = new Car("Honda", "Civic");
function Car(make, model) {
this.getMake = function( ) { return make; }
this.getModel = function( ) { return model; }
}
是否有方法验证提供给构造函数的make和model是字符串?例如,我希望用户能够说
myCar = new Car("Honda", "Civic");
myCar = new Car(4, 5.5);
但我不想让用户说
myCar = new Car("Honda", "Civic");
myCar = new Car(4, 5.5);
我想你要找的是接线员的类型 或者,只需将您得到的内容转换为其字符串表示形式:
function Car(make, model) {
make = String(make);
model = String(model);
this.getMake = function( ) { return make; };
this.getModel = function( ) { return model; };
}
通常最好使用
String()
而不是.toString()
,因为无法保证对象具有toString
并且其toString
是可调用的。我还建议用分号终止函数表达式,以避免任何令人讨厌的行为。别忘了向变量声明。