使用原型链 或者class 实现一个计算器完成链式调用

1.使用class类
复制代码
class myCalculator{
    constructor(value){
        this.value = value
    }
    add(newValue){
        this.value = this.value + newValue
        return this
    }
    reduction(newValue){
        this.value = this.value - newValue
        return this
    }
    take(newValue){
        this.value = this.value * newValue
        return this
    }
    division(newValue){
        this.value = this.value / newValue
        return this
    }
}
var num = new myCalculator(1)
var a = num.add(2).reduction(2).take(5).division(2)
console.log(a);
复制代码
2.使用原型链
复制代码
function myCalculator(num){
    this.num = num;
}
myCalculator.prototype.add = function(newNum){
    this.num = this.num + newNum
    return this
}
myCalculator.prototype.redu = function(newNum){
    this.num = this.num - newNum
    return this
}
myCalculator.prototype.take = function(newNum){
    this.num = this.num * newNum
    return this
}
myCalculator.prototype.division = function(newNum){
    this.num = this.num / newNum
    return this
}
var sum = new myCalculator(5);
sum.add(2).redu(3).take(3).division(3)
console.log(sum)  //打印4
复制代码

 

posted @   暴龙机甲兽  阅读(604)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示