JavaScript中的构造函数和方法链接

Set*_*hen 1 javascript

我正在尝试与我的构造函数一起使方法链工作,但我不确定如何去做.这是我到目前为止的代码:

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());
Run Code Online (Sandbox Code Playgroud)

我试图在add方法的返回值上调用multiply方法.我知道有一些显而易见的事我不做,但我不确定它是什么.

有什么想法吗?

Bud*_*hiP 13

您不应该返回表达式的结果.而是返回此.

Points.prototype = {

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

}
Run Code Online (Sandbox Code Playgroud)

然后像这样使用它: console.log(some.add().multiply().result);

  • @Sethen:`.multiply()`返回`this`.所以它与访问`this.result`或`some.result`是一样的.`.add`也返回`this`,这就是为什么你可以在它上面调用`multiple`,这也是对象的属性.这是同一件事. (2认同)