2012-11-18 41 views
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()); 

我想调用add方法的返回值的乘法方法。我知道有些事情显而易见,我没有做,但我不确定它是什么。

有什么想法?

回答

12

您不应该返回表达式的结果。相反,返回这个。

Points.prototype = { 

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

} 

,然后用它是这样的:console.log(some.add().multiply().result);

+0

啊,当然,当然。完美,这就是我一直在寻找的。我想知道为什么在它的结尾有'.result'。我知道它会返回'result'属性..但是,如何? – Sethen

+1

@ Sethen:那是一个很好的Sidharth编辑。在.multiply()调用结束时,您将返回Point实例,并在该对象上解析.result属性,从而为您提供结果属性的当前值 – BuddhiP

+2

@Sethen:'.multiply()'返回'this'。所以和访问'this.result'或'some.result'一样。 '.add'也返回'this',这就是为什么你可以调用'multiple',这也是对象的一个​​属性。这是同一件事。 –