如何编写像这样的JavaScript对象

时间:2016-05-21 16:07:26

标签: javascript oop

如何编写Object以使用此对象,如下所示

var cal = new calculator;

cal.add(10).add(20).miniz(2).div(2);

console.log(cal.result()); // result 14

4 个答案:

答案 0 :(得分:3)

在这里,这是一种方法:

My Example

var calculator = function() {
  this.curr = 0;
  this.add = function(n) {
    this.curr += n;
    return this; // returning this at the end of each method is the key to chaining
  };
  this.miniz = function(n) {
    this.curr -= n;
    return this;
  };
  this.div = function(n) {
    this.curr = this.curr / n;
    return this;
  };
  this.result = function() {
    return this.curr;
  };
};

您需要将实例化更改为:

var cal = new calculator();

答案 1 :(得分:1)

只是为了让你开始:

function Calculator() {
    var value = 0;
    this.add = function (v) {
        value += v;
        return this;
    };
    this.result = function () {
        return value;
    };
}

var cal = new Calculator;

console.log(cal.add(10).result()); // result 10

答案 2 :(得分:1)

可能这会有所帮助。

var Calc = function(){
   this.value = 0;  
};

Calc.prototype.add = function(val){
    this.value += val;
    return this;
};

然后您就可以使用new Calc().add(100).add(100)

但在确定理解原型制作是如何工作之前,

表示参考:a sample

答案 3 :(得分:0)

function calculator(){
    this.val = 0;
    this.add = function(num){
        this.val += num;
        return this;
    };

    this.miniz = function(num){
        this.val -= num;
        return this;
    };

    this.div = function(num){
        this.val /= num;
        return this;  
    };

    this.result = function(){
        return this.val;
    };
}