嘗試理解鏈式方法,可以像數學一樣,也可以像cheerio/jQuery一樣,當事情變得太長時,我會縮短并替換為自己的方法。
//這將幫助我在復雜的方法中獲得縮短的方法,并應用于項目 function getValue() { this.add = function(y) { return x + y; }; this.mult = function(y) { return x * y; }; return this; }; //不使用new操作符的實例會很有趣 const price1 = getValue(8); const price2 = getValue(2).add(1); const price3 = getValue(5).add(3).mult(2); //不重要,但是推進更遠: const price4 = getValue().add(2).add(2); const price5 = getValue(5).add(2).add(2); console.log(price1); // 期望值為8 console.log(price2); // 期望值為3 console.log(price3); // 期望值為16 console.log(price4); // 期望值為4 console.log(price5); // 期望值為9
我通過為y添加默認值來改進了上述代碼,以防止在未提供y時結果為“nan”??傮w而言,這是一個很好的答案。
function getValue(x = 0) { this.x = x; this.add = function(y = 0) { this.x += y; return this; }; this.mult = function(y = 1) { this.x *= y; return this; }; this.value = function() { return this.x; }; return this; }; const price1 = getValue(8).value(); const price2 = getValue(2).add(1).value(); const price3 = getValue(5).add(3).mult(2).value(); const price4 = getValue().add(2).add(2).value(); const price5 = getValue(5).add(2).add(2).value(); console.log(price1); // 期望輸出 8 console.log(price2); // 期望輸出 3 console.log(price3); // 期望輸出 16 console.log(price4); // 期望輸出 4 console.log(price5); // 期望輸出 9
你需要使用 getValue
函數來接收一個參數 x
。此外,你的鏈式函數應該返回 this
。最后,你需要一個函數來解包值,即 value()
。
請注意,在 price4
中,你沒有傳入初始值,所以可以默認為 0
。
function getValue(x = 0) { this.x = x; this.add = function(y) { this.x += y; return this; }; this.mult = function(y) { this.x *= y; return this; }; this.value = function() { return this.x; }; return this; }; const price1 = getValue(8).value(); const price2 = getValue(2).add(1).value(); const price3 = getValue(5).add(3).mult(2).value(); const price4 = getValue().add(2).add(2).value(); const price5 = getValue(5).add(2).add(2).value(); console.log(price1); // 期望值為 8 console.log(price2); // 期望值為 3 console.log(price3); // 期望值為 16 console.log(price4); // 期望值為 4 console.log(price5); // 期望值為 9