我有一个代表汽车的 JavaScript 类,它是使用两个参数构造的,这两个参数代表汽车的品牌和型号:
function Car(make, model) {
this.getMake = function( ) { return make; }
this.getModel = function( ) { return model; }
}
有没有办法验证提供给构造函数的品牌和型号是否是字符串?例如,我希望用户能够说,
myCar = new Car("Honda", "Civic");
但我不希望用户能够说,
myCar = new Car(4, 5.5);
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; };
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)