Trying to understand chained methods, either like math or cheerio/jQuery, when things get too long I shorten and replace with my own methods.
//这将帮助我在复杂的方法中获得缩短的方法,并应用于项目 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
I improved the above code by adding a default value for y to prevent the result from being "nan" when y is not provided. Overall, this is a great answer.
You need to use the
getValue
function to receive a parameterx
. Additionally, your chained functions should returnthis
. Finally, you need a function to unpack the value, i.e.value()
.Please note that in
price4
, you do not pass in the initial value, so it can default to0
.