js原型链实现计算器
使用原型链实现计算器
通过原型链可以实现一个基本的计算器功能,利用原型继承来共享方法和属性。以下是一个基于原型链的计算器实现示例:
// 定义计算器构造函数
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();
const result = calc.add(5).multiply(2).subtract(3).divide(2).getValue();
console.log(result); // 输出: 3.5
实现说明
-
构造函数定义
创建Calculator构造函数,初始化currentValue为0,用于存储当前计算结果。 -
方法链式调用
每个计算方法都返回this,支持链式调用,可以连续执行多个操作。 -
原型方法
所有方法都定义在Calculator.prototype上,所有实例共享这些方法,节省内存。 -
基本运算功能
实现了加(add)、减(subtract)、乘(multiply)、除(divide)四种基本运算,以及清除(clear)和获取结果(getValue)功能。 -
使用方法
创建实例后可以通过链式调用执行连续运算,最后通过getValue获取结果。
扩展功能
可以通过原型链继续扩展计算器的功能:

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;
};
这种实现方式利用了JavaScript的原型继承特性,使代码结构清晰且易于扩展。





