JavaScript构造函数参数类型 [英] JavaScript constructor parameter types

查看:154
本文介绍了JavaScript构造函数参数类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个代表汽车的JavaScript类,它使用两个参数构造,它们表示汽车的品牌和型号:

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; }
}

有没有办法验证make和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);


推荐答案

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; };
}

这篇关于JavaScript构造函数参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆