2009-10-10 129 views
2

我代表一辆车,这是使用两个参数,这代表了汽车的品牌和型号构成的JavaScript类: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); 
+0

不要忘记申报您的变量。 – kangax 2009-10-11 06:38:34

回答

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

通常最好使用'String()'而不是' .toString()',因为实际上不能保证对象具有'toString'并且它的'toString'是可调用的。我也建议用分号终止函数表达式 - 以避免任何讨厌的行为。 – kangax 2009-10-11 06:35:54

+0

@ kangax,根据您的建议进行编辑。 – James 2009-10-11 09:16:35