简体   繁体   中英

Constructors and method chaining in JavaScript

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM