2012-11-18 40 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',這也是對象的一個​​屬性。這是同一件事。 –