views:

123

answers:

2

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 example, 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);
A: 

I think what you're looking for is the typeof operator. https://developer.mozilla.org/en/Core%5FJavaScript%5F1.5%5FReference/Operators/Special%5FOperators/typeof%5FOperator

Hans Lawrenz
+3  A: 
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; };
}
J-P
It's usually better to use `String(<smth>)` instead of `<smth>.toString()`, since there's really no guarantee that an object has `toString` and that its `toString` is callable. I would also suggest to terminate function expressions with semicolons — to avoid any nasty behavior.
kangax
@kangax, edited as per your recommendations.
J-P