其他分享
首页 > 其他分享> > 使用原型链 或者class 实现一个计算器完成链式调用

使用原型链 或者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

标签:return,myCalculator,链式,value,newValue,num,newNum,计算器,class
来源: https://www.cnblogs.com/bljjs/p/15913378.html