面试题答案
一键面试- 基本思路:
- 在JavaScript中,函数本身不支持传统意义上的重载,因为函数名是唯一确定函数的标识。
- 可以通过检查传入参数的个数或类型来实现类似重载的效果。在函数内部使用
arguments.length
获取参数个数,或者使用typeof
等方法检查参数类型,然后根据不同情况执行不同的逻辑。
- 示例代码:
class Calculator {
add() {
if (arguments.length === 1) {
return arguments[0] + 10;
} else if (arguments.length === 2) {
return arguments[0] + arguments[1];
}
}
}
// 使用示例
let calculator = new Calculator();
console.log(calculator.add(5)); // 输出15
console.log(calculator.add(3, 7)); // 输出10