1.使用原型链方法
function myCalculator(num) {
this.num = num;
}
myCalculator.prototype.add = function (n) {
this.num = this.num + n
return this
}
myCalculator.prototype.minus = function (n) {
this.num = this.num - n
return this
}
myCalculator.prototype.multi = function (n) {
this.num = this.num * n
return this
}
myCalculator.prototype.div = function (n) {
this.num = this.num / n
return this
}
let sum = new myCalculator(123);
sum.add(1).minus(4);
console.log(sum.num);
2.使用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
}
}
let num = new MyCalculator (1)
let afterDate = num.add(2).reduction(2).take(5).division(2)
console.log(afterDate.value);