函數透過鍊式方法
P粉916553895
P粉916553895 2023-09-06 20:16:14
0
2
574

嘗試理解鍊式方法,可以像數學一樣,也可以像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學習者快速成長!