函数通过链式方法
P粉916553895
P粉916553895 2023-09-06 20:16:14
0
2
573

尝试理解链式方法,可以像数学一样,也可以像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
P粉916553895
P粉916553895

全部回复(2)
P粉884548619

我通过为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
P粉739079318

你需要使用 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
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!