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
P粉8845486192023-09-07 19:35:42
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.
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
P粉7390793182023-09-07 12:11:26
You need to use the getValue
function to receive a parameter x
. Additionally, your chained functions should return this
. 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 to 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