MST

星途 面试题库

面试题:JavaScript 实现类构造函数重载时如何处理参数类型兼容性及错误处理

假设你正在使用 JavaScript 模拟类构造函数重载。要求在构造函数重载实现中,不仅要能根据不同参数数量做出不同初始化操作,还要处理参数类型兼容性问题,比如传入一个预期为数字但实际是字符串的参数时,要给出合适的错误提示或进行类型转换(如果合理的话)。请编写相应代码,并解释关键实现步骤。
46.0万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试

代码实现

function Person() {
    // 这里处理无参数调用
    if (arguments.length === 0) {
        this.name = 'Unknown';
        this.age = 0;
    }
    // 处理单个参数调用
    else if (arguments.length === 1) {
        if (typeof arguments[0] ==='string') {
            this.name = arguments[0];
            this.age = 0;
        } else if (typeof arguments[0] === 'number') {
            this.name = 'Unknown';
            this.age = arguments[0];
        } else {
            throw new Error('Unsupported argument type for single - argument constructor.');
        }
    }
    // 处理两个参数调用
    else if (arguments.length === 2) {
        if (typeof arguments[0] ==='string' && typeof arguments[1] === 'number') {
            this.name = arguments[0];
            this.age = arguments[1];
        } else {
            throw new Error('Invalid argument types for two - argument constructor.');
        }
    } else {
        throw new Error('Unsupported number of arguments.');
    }
}

// 测试代码
try {
    const person1 = new Person();
    console.log(person1.name, person1.age);

    const person2 = new Person('John');
    console.log(person2.name, person2.age);

    const person3 = new Person(30);
    console.log(person3.name, person3.age);

    const person4 = new Person('Jane', 25);
    console.log(person4.name, person4.age);

    // 下面这行会抛出错误
    const person5 = new Person('Invalid', 'not a number');
} catch (error) {
    console.error(error.message);
}

关键实现步骤解释

  1. 判断参数数量
    • 使用 arguments.length 来判断传入构造函数的参数数量。根据不同的参数数量进入不同的处理逻辑。
  2. 处理参数类型
    • 在每个参数数量对应的处理逻辑中,使用 typeof 操作符检查参数的类型。
    • 如果参数类型符合预期,则进行相应的初始化操作。例如,当有两个参数时,确保第一个是字符串,第二个是数字才进行初始化。
    • 如果参数类型不符合预期,抛出合适的错误提示,如 'Unsupported argument type for single - argument constructor.''Invalid argument types for two - argument constructor.',以提示调用者参数类型有误。
  3. 无参数情况
    • arguments.length === 0 时,为对象设置默认的 nameage 值。
  4. 单个参数情况
    • 判断单个参数的类型,如果是字符串,则将其作为 nameage 设置为 0;如果是数字,则将其作为 agename 设置为 'Unknown'。若类型既不是字符串也不是数字,则抛出错误。
  5. 两个参数情况
    • 确保第一个参数是字符串,第二个参数是数字,才分别赋值给 nameage,否则抛出错误。