嘗試?yán)斫忮€式方法,可以像數(shù)學(xué)一樣,也可以像cheerio/jQuery一樣,當(dāng)事情變得太長(zhǎng)時(shí),我會(huì)縮短並替換為自己的方法。
//這將幫助我在復(fù)雜的方法中獲得縮短的方法,并應(yīng)用于項(xiàng)目 function getValue() { this.add = function(y) { return x + y; }; this.mult = function(y) { return x * y; }; return this; }; //不使用new操作符的實(shí)例會(huì)很有趣 const price1 = getValue(8); const price2 = getValue(2).add(1); const price3 = getValue(5).add(3).mult(2); //不重要,但是推進(jìn)更遠(yuǎn): 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ù)設(shè)值來改進(jìn)了上述程式碼,以防止在未提供y時(shí)結(jié)果為「nan」??傮w而言,這是一個(gè)很好的答案。
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
函數(shù)來接收一個(gè)參數(shù) x
。此外,你的鍊式函數(shù)應(yīng)該回傳 this
。最後,你需要一個(gè)函數(shù)來解包值,即 value()
。
請(qǐng)注意,在 price4
中,你沒有傳入初始值,所以可以預(yù)設(shè)為 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