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