Ral*_*lph 3 javascript constructor types
我有一个代表汽车的 JavaScript 类,它是使用两个参数构造的,代表汽车的品牌和型号:
function Car(make, model) {
this.getMake = function( ) { return make; }
this.getModel = function( ) { return model; }
}
Run Code Online (Sandbox Code Playgroud)
有没有办法验证提供给构造函数的品牌和型号是字符串?例如,我希望用户能够说,
myCar = new Car("Honda", "Civic");
Run Code Online (Sandbox Code Playgroud)
但我不希望用户能够说,
myCar = new Car(4, 5.5);
Run Code Online (Sandbox Code Playgroud)
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; };
}
Run Code Online (Sandbox Code Playgroud)
或者,只需将您获得的任何内容转换为其字符串表示形式:
function Car(make, model) {
make = String(make);
model = String(model);
this.getMake = function( ) { return make; };
this.getModel = function( ) { return model; };
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5900 次 |
| 最近记录: |