我有一个代表汽车的JavaScript类,它使用两个参数构建,代表汽车的品牌和型号:
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);
答案 0 :(得分:4)
function Car(make, model) {
if (typeof make !== 'string' || typeof model !== 'string') {
throw new Error('Strings expected... blah');
}
this.getMake = function( ) { return make; };
this.getModel = function( ) { return model; };
}
或者,只需将您获得的任何内容转换为其字符串表示形式:
function Car(make, model) {
make = String(make);
model = String(model);
this.getMake = function( ) { return make; };
this.getModel = function( ) { return model; };
}
答案 1 :(得分:0)