计算器函数不起作用,正在显示不确定的函数



在函数下无法正常工作,并且显示"添加不确定"。我正在通过链接函数调用来计算。

var calc = {
  x: 5,
  add: function(num) {
    x = x + num;
    return x;
  },
  sub: function(num) {
    x = x - num;
    return x;
  },
  set: function(num) {
    x = num;
    return x;
  },
  print: function() {
    console.log(x);
  }
}
calc.set(5).add(3).sub(2).add(10).print();

您需要返回对calc而不是数字的引用以允许链接,还请使用this参考x值:

var calc = {
  x : 5,
  add: function(num){
    this.x = this.x+num;
    return this;
  },
  sub :function(num){
    this.x =this.x-num;
    return this;
  },
  set :function(num){
    this.x= num;
    return this;
  },
  print : function(){
    console.log(this.x);
  }
}
calc.set(5).add(3).sub(2).add(10).print();

这是class语法的ES6版本:

class Calc {
  constructor(x = 0) {
    this.x = x;
  }
  add(num) {
    this.x = this.x + num;
    
    return this;
  }
  
  sub(num) {
    this.x = this.x - num;
    
    return this;
  }
  
  set(num) {
    this.x = num;
    
    return this;
  }
  
  print() {
    console.log(this.x);
  }
}
new Calc().set(5).add(3).sub(2).add(10).print();
// or with constructor
new Calc(5).add(3).sub(2).add(10).print();

我宁愿做这个 :

var Calc = function (x) {
  this.x = x;
};
Calc.prototype = {
  add: function (y) {
    this.x += y;
    return this;
  },
  sub: function (y) {
    this.x -= y;
    return this;
  },
  valueOf: function () {
    return this.x;
  },
  toString: function () {
    return (+this) + "";
  },
  print : function () {
    console.log(this.toString());
    return this;
  }
};
function calc (x) {
  return new Calc(x);
}
calc(1).add(
  calc(5).add(3).sub(2).add(10).print()
).print();

最新更新