1

I am trying to make method chaining work in conjunction with my constructors, but I am not exactly sure how to go about it. Here is my code thus far:

function Points(one, two, three) {
this.one = one;
this.two = two;
this.three = three;
}

Points.prototype = {

add: function() {
    return this.result = this.one + this.two + this.three;
},
multiply: function() {
    return this.result * 30;
}

}

var some = new Points(1, 1, 1);
console.log(some.add().multiply());

I am trying to call the multiply method on the return value of the add method. I know there is something obvious that I am not doing, but I am just not sure what it is.

Any thoughts?

1 Answer 1

13

You should not return the result of the expression. Instead return this.

Points.prototype = {

    add: function() {
        this.result = this.one + this.two + this.three;
        return this;
    },
    multiply: function() {
        this.result = this.result * 30;
        return this;
    }

}

And then use it like this: console.log(some.add().multiply().result);

Sign up to request clarification or add additional context in comments.

4 Comments

Ahh, of course, of course. Perfect, this is what I was looking for. I am wondering why there is the .result on the end of it. I know it returns the result property.. But, how?
@Sethen: Well, its a good edit by Sidharth. at the end of .multiply() call, you return you Point instance, and .result property is resolved on that object, giving you the current value of the result property
@Sethen: .multiply() returns this. So it's the same as accessing this.result or some.result. .add returns this as well, that's why you can call multiple on it, which is also a property of the object. It's the same thing.
Ahh, that makes sense. It's just a property access expression basically. Perfect, thanks!

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.