0

How to write an Object for using this object like below

var cal = new calculator;

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

console.log(cal.result()); // result 14
7
  • return this; will be useful in your construction. Commented May 21, 2016 at 16:08
  • 4
    a constructor would be useful. Commented May 21, 2016 at 16:08
  • how exactly?? @NinaScholz Commented May 21, 2016 at 16:09
  • 2
    This isn't a how-to tutorial service. Question is too broad Commented May 21, 2016 at 16:11
  • 1
    You really ought to show us you can create the basics of an object with methods. Then object chaining is simply done by adding a return this to every method that you want to be chainable and storing intermediate results in the object's instance data. We don't just write code for you here. We help you solve problems in code you've already tried to write. Commented May 21, 2016 at 16:11

4 Answers 4

3

Here you go, this is one way to do it:

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;
  };
};

You need to change the instantiation to this:

var cal = new calculator();
Sign up to request clarification or add additional context in comments.

1 Comment

You could use prototype to define the methods.
1

Just to get you started:

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

Comments

1

may be this is will help some what..

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

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

then you can use like new Calc().add(100).add(100)

but before make sure understood how prototyping is working,

for ref : a sample

Comments

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;
    };
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.