尝试理解链式方法,可以像数学一样,也可以像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
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我通过为y添加默认值来改进了上述代码,以防止在未提供y时结果为“nan”。总体而言,这是一个很好的答案。
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