MST

星途 面试题库

面试题:JavaScript 中如何模拟类构造函数重载实现不同参数初始化

在 JavaScript 中,没有原生的构造函数重载机制。请你编写代码,通过一种合理的方式来模拟实现构造函数的重载,使得一个类可以根据传入参数的数量或类型不同,执行不同的初始化逻辑。例如,当传入一个字符串参数时,进行一种初始化;传入一个数字参数时,进行另一种初始化。
14.2万 热度难度
编程语言JavaScript

知识考点

AI 面试

面试题答案

一键面试
function MyClass() {
    const args = Array.from(arguments);
    if (args.length === 1 && typeof args[0] ==='string') {
        this.initWithString(args[0]);
    } else if (args.length === 1 && typeof args[0] === 'number') {
        this.initWithNumber(args[0]);
    }
}

MyClass.prototype.initWithString = function (str) {
    this.strValue = str;
    console.log(`Initialized with string: ${this.strValue}`);
};

MyClass.prototype.initWithNumber = function (num) {
    this.numValue = num;
    console.log(`Initialized with number: ${this.numValue}`);
};

// 测试
const instance1 = new MyClass('test string');
const instance2 = new MyClass(42);