JavaScript constructor parameter types
I have a JavaScript class representing a car, which is constructed using two parameters, which represent the make and model of the car:
function Car(make, model) {
this.getMake = function( ) { return make; }
this.getModel = function( ) { return model; }
}
Is there a way to verify that the make and model supplied to the constructor are strings? For exampl开发者_运维知识库e, I want the user to be able to say,
myCar = new Car("Honda", "Civic");
But I don't want the user to be able to say,
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; };
}
Or, just convert whatever you get to its string representation:
function Car(make, model) {
make = String(make);
model = String(model);
this.getMake = function( ) { return make; };
this.getModel = function( ) { return model; };
}
I think what you're looking for is the typeof operator. https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Operators/Special_Operators/typeof_Operator
精彩评论