js原型链实现加减乘除
原型链实现加减乘除的方法
在JavaScript中,可以通过原型链扩展内置对象的功能,例如为Number或Object原型添加加减乘除方法。以下是具体实现方式:
为Number原型添加方法
通过扩展Number.prototype,可以直接在数字实例上调用自定义的加减乘除方法。

// 加法
Number.prototype.add = function(num) {
return this + num;
};
// 减法
Number.prototype.subtract = function(num) {
return this - num;
};
// 乘法
Number.prototype.multiply = function(num) {
return this * num;
};
// 除法
Number.prototype.divide = function(num) {
if (num === 0) throw new Error('除数不能为0');
return this / num;
};
// 使用示例
const result = (5).add(3).subtract(2).multiply(4).divide(2);
console.log(result); // 输出: 12
为Object原型添加通用方法
若希望更通用地处理多种数据类型,可以扩展Object.prototype,但需注意可能引发全局污染问题。

// 加法
Object.prototype.add = function(num) {
return this + num;
};
// 减法
Object.prototype.subtract = function(num) {
return this - num;
};
// 乘法
Object.prototype.multiply = function(num) {
return this * num;
};
// 除法
Object.prototype.divide = function(num) {
if (num === 0) throw new Error('除数不能为0');
return this / num;
};
// 使用示例
const result = (5).add(3).subtract(2).multiply(4).divide(2);
console.log(result); // 输出: 12
注意事项
- 原型污染风险:直接修改内置对象的原型可能影响其他代码,尤其是在大型项目中。建议仅在必要时使用,或通过模块化方式隔离。
- 类型检查:实现时应验证操作数的类型,避免非数字类型的意外行为。
- 错误处理:除法需检查除数是否为0,抛出明确错误。
替代方案:工具类
为避免原型污染,可以封装独立的工具类实现功能:
class Calculator {
static add(a, b) { return a + b; }
static subtract(a, b) { return a - b; }
static multiply(a, b) { return a * b; }
static divide(a, b) {
if (b === 0) throw new Error('除数不能为0');
return a / b;
}
}
// 使用示例
const sum = Calculator.add(5, 3);
console.log(sum); // 输出: 8
链式调用扩展
若需链式调用,可以结合返回新实例的方式:
class MathChain {
constructor(value) {
this.value = value;
}
add(num) { return new MathChain(this.value + num); }
subtract(num) { return new MathChain(this.value - num); }
multiply(num) { return new MathChain(this.value * num); }
divide(num) {
if (num === 0) throw new Error('除数不能为0');
return new MathChain(this.value / num);
}
}
// 使用示例
const result = new MathChain(5).add(3).subtract(2).multiply(4).divide(2).value;
console.log(result); // 输出: 12
以上方法提供了不同场景下的实现选择,开发者可根据项目需求权衡使用原型链或独立工具类。





