JavaScript 类中可以返回的 Setter

问题描述 投票:0回答:1

所以我在 JavaScript 中有一个类 XYZ,它的功能很少:

class XYZ{
    constructor(){
        this.text=null;
    }
    f1(){
      // Do Something
      return this;
    }

    f2(){
      // Do Something
      return this;
    }

    f3(txt=null){
      if(txt){
          this.text=txt;
          this.show();
      }
      // Do Something
      return this;
    }

    show(){
      console.log(this.text)
    }
}

const obj = new XYZ();
obj.f1().f2().f3("Hello").f1();
obj.f1().f2().f3().f2();

我想要实现的是,如果没有文本传递给f3,我想跳过括号并像getter一样使用它:

const obj = new XYZ();
obj.f1().f2().f3("Hello").f1();
obj.f1().f2().f3.f2();

我可以使用 getter 和 setter 实现类似的功能,但我不想破坏链调用。如果不传递值,或者一起使用相同名称的 getter 和方法,有没有一种方法可以跳过大括号? 谢谢

javascript function class methods getter-setter
1个回答
0
投票

您可以采用构建器模式来消除不需要参数的调用。

请注意,您应该始终使用括号来表示函数调用。访问对象的属性不应产生任何副作用。我们不是在引用该函数,而是在调用它,因此您需要括号;即使我们不向它传递任何参数。

构建器允许我们在构建最终对象之前以任何我们想要的方式修改变量。

class Point3D {
  constructor(x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;
  }
  toString() {
    return `[Point3D(x=${this.x},y=${this.y},z=${this.z})]`;
  }
}

class _Point3D_Builder {
  constructor() {
    this._x = 0;
    this._y = 0;
    this._z = 0;
  }
  x(_x) {
    this._x = _x;
    return this;
  }
  y(_y) {
    this._y = _y;
    return this;
  }
  z(_z) {
    this._z = _z;
    return this;
  }
  scale(factor) {
    this._x *= factor;
    this._y *= factor;
    this._z *= factor;
    return this;
  }
  scaleBy2() {
    return this.scale(2.0);
  }
  build() {
    return new Point3D(this._x, this._y, this._z);
  }
}

Point3D.Builder = _Point3D_Builder;

const a = new Point3D.Builder().x(1).y(2).build();
const b = new Point3D.Builder().x(3).z(5).scaleBy2().build();

console.log(a.toString()); // [Point3D(x=1,y=2,z=0)]
console.log(b.toString()); // [Point3D(x=6,y=0,z=10)]
.as-console-wrapper { top: 0; max-height: 100% !important; }

更新:我找到了一个很好的教程,使用

Car
类演示了这一点:

“在 JavaScript 中使用构建器模式”

© www.soinside.com 2019 - 2024. All rights reserved.