js原型链实现计算器
原型链实现计算器的基本思路
使用JavaScript的原型链机制可以实现一个计算器功能。原型链允许对象继承另一个对象的属性和方法,通过这种方式可以构建一个具有基本计算功能的对象,并通过原型扩展更复杂的计算功能。
创建基础计算器对象
定义一个基础计算器构造函数,包含加、减、乘、除等基本方法:

function BasicCalculator() {}
BasicCalculator.prototype.add = function(a, b) {
return a + b;
};
BasicCalculator.prototype.subtract = function(a, b) {
return a - b;
};
BasicCalculator.prototype.multiply = function(a, b) {
return a * b;
};
BasicCalculator.prototype.divide = function(a, b) {
if (b === 0) throw new Error("Division by zero");
return a / b;
};
扩展高级计算功能
通过原型链扩展更高级的计算功能,例如平方、开方等:
function AdvancedCalculator() {}
// 继承BasicCalculator的原型
AdvancedCalculator.prototype = Object.create(BasicCalculator.prototype);
AdvancedCalculator.prototype.square = function(x) {
return this.multiply(x, x);
};
AdvancedCalculator.prototype.sqrt = function(x) {
if (x < 0) throw new Error("Square root of negative number");
return Math.sqrt(x);
};
使用计算器对象
创建实例并调用方法:

const calc = new AdvancedCalculator();
console.log(calc.add(5, 3)); // 8
console.log(calc.subtract(5, 3)); // 2
console.log(calc.square(4)); // 16
console.log(calc.sqrt(16)); // 4
原型链的验证
可以通过instanceof或检查原型链验证继承关系:
console.log(calc instanceof BasicCalculator); // true
console.log(calc instanceof AdvancedCalculator); // true
动态扩展原型
原型链允许动态扩展功能,例如添加百分比计算:
AdvancedCalculator.prototype.percentage = function(value, total) {
return this.divide(this.multiply(value, 100), total);
};
console.log(calc.percentage(25, 200)); // 12.5
注意事项
- 原型链继承可能导致方法覆盖问题,需注意方法命名冲突。
- 使用
Object.create确保原型链正确建立,避免直接修改prototype导致问题。 - 错误处理(如除零或负数开方)应提前检查并抛出异常。






