代码实现
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);
}
关键实现步骤解释
- 判断参数数量:
- 使用
arguments.length
来判断传入构造函数的参数数量。根据不同的参数数量进入不同的处理逻辑。
- 处理参数类型:
- 在每个参数数量对应的处理逻辑中,使用
typeof
操作符检查参数的类型。
- 如果参数类型符合预期,则进行相应的初始化操作。例如,当有两个参数时,确保第一个是字符串,第二个是数字才进行初始化。
- 如果参数类型不符合预期,抛出合适的错误提示,如
'Unsupported argument type for single - argument constructor.'
或 'Invalid argument types for two - argument constructor.'
,以提示调用者参数类型有误。
- 无参数情况:
- 当
arguments.length === 0
时,为对象设置默认的 name
和 age
值。
- 单个参数情况:
- 判断单个参数的类型,如果是字符串,则将其作为
name
,age
设置为 0;如果是数字,则将其作为 age
,name
设置为 'Unknown'
。若类型既不是字符串也不是数字,则抛出错误。
- 两个参数情况:
- 确保第一个参数是字符串,第二个参数是数字,才分别赋值给
name
和 age
,否则抛出错误。