js原型链实现计算器
使用原型链实现计算器
在JavaScript中,可以通过原型链实现一个基础的计算器功能。以下是一个基于原型链的计算器实现示例:

定义构造函数
function Calculator() {
this.currentValue = 0;
}
添加原型方法
Calculator.prototype.add = function(num) {
this.currentValue += num;
return this;
};
Calculator.prototype.subtract = function(num) {
this.currentValue -= num;
return this;
};
Calculator.prototype.multiply = function(num) {
this.currentValue *= num;
return this;
};
Calculator.prototype.divide = function(num) {
this.currentValue /= num;
return this;
};
Calculator.prototype.getValue = function() {
return this.currentValue;
};
Calculator.prototype.clear = function() {
this.currentValue = 0;
return this;
};
使用方法示例
const calc = new Calculator();
calc.add(5).multiply(2).subtract(3).divide(2);
console.log(calc.getValue()); // 输出: 3.5
实现链式调用
通过在每个方法中返回this,可以实现链式调用。每个方法都会修改currentValue,然后返回计算器实例本身,以便继续调用其他方法。
扩展功能
可以继续扩展计算器的功能,例如添加幂运算、平方根等:
Calculator.prototype.power = function(num) {
this.currentValue = Math.pow(this.currentValue, num);
return this;
};
Calculator.prototype.sqrt = function() {
this.currentValue = Math.sqrt(this.currentValue);
return this;
};
注意事项
- 所有方法都会修改
currentValue的状态 - 除法操作需要注意除数为0的情况
- 浮点数运算可能存在精度问题
- 可以通过添加历史记录功能来增强计算器
这种实现方式展示了JavaScript原型链的基本用法,通过原型共享方法可以节省内存,同时保持实例间的独立性。







