3

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);
1
  • Don't forget to declare to your variables. Commented Oct 11, 2009 at 6:38

2 Answers 2

7
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; };
}
Sign up to request clarification or add additional context in comments.

1 Comment

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.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.