js原型链实现加减乘除
原型链实现加减乘除
在JavaScript中,可以通过原型链扩展内置对象(如Number或Object)来实现自定义的加减乘除方法。以下是具体实现方式:

扩展Number.prototype
通过修改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) {
return this / num;
};
// 使用示例
const result = (5).add(3).subtract(2).multiply(4).divide(2);
console.log(result); // 输出: 12
扩展Object.prototype(不推荐)
虽然技术上可行,但扩展Object.prototype会影响所有对象,可能导致不可预期的副作用:
Object.prototype.add = function(num) {
return this + num;
};
// 使用示例(需注意类型转换)
console.log(5..add(3)); // 输出: 8
链式调用实现
通过返回this或计算结果,可以实现链式调用:
Number.prototype.chainAdd = function(num) {
return this + num;
};
Number.prototype.chainMultiply = function(num) {
return this * num;
};
// 链式调用示例
const chainResult = (2).chainAdd(3).chainMultiply(4);
console.log(chainResult); // 输出: 20
注意事项
- 扩展内置原型可能与其他库冲突,需谨慎使用。
- 方法命名应避免与未来JavaScript标准冲突(如加
$前缀)。 - 浮点数运算需处理精度问题(如
0.1 + 0.2 !== 0.3)。
完整代码示例
// 安全扩展Number原型
if (!Number.prototype.$add) {
Number.prototype.$add = function(num) {
return this + num;
};
}
if (!Number.prototype.$subtract) {
Number.prototype.$subtract = function(num) {
return this - num;
};
}
// 使用示例
const safeResult = (10).$add(5).$subtract(3);
console.log(safeResult); // 输出: 12
通过原型链扩展实现数学运算时,需权衡便利性与代码安全性,建议仅在可控环境中使用。






