开发者

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜