berfungsi melalui kaedah rantai
P粉916553895
P粉916553895 2023-09-06 20:16:14
0
2
575

Cuba untuk memahami kaedah berantai, sama ada seperti matematik atau cheerio/jQuery, apabila perkara menjadi terlalu lama saya memendekkan dan menggantikan dengan kaedah saya sendiri.

//这将帮助我在复杂的方法中获得缩短的方法,并应用于项目

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

membalas semua(2)
P粉884548619

Saya menambah baik kod di atas dengan menambahkan nilai lalai untuk y untuk mengelakkan hasil daripada menjadi "nan" apabila y tidak disediakan. Secara keseluruhan, ini adalah jawapan yang bagus.

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

Anda perlu menggunakan getValue 函数来接收一个参数 x。此外,你的链式函数应该返回 this。最后,你需要一个函数来解包值,即 value().

Sila ambil perhatian bahawa dalam 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
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan
Tentang kita Penafian Sitemap
Laman web PHP Cina:Latihan PHP dalam talian kebajikan awam,Bantu pelajar PHP berkembang dengan cepat!