如何在面向对象 Javascript 中进行方法链接?

how to do method chaining in object oriented Javascript?

我正在尝试进行方法链接,但在第二种方法上 returning 未定义。我在每个函数中添加了 return 所以我不确定为什么它会 return 未定义。这是我的代码

var expertSurfLevel = []
var noviceSurfLevel = []
var IntermediateSurfLevel = []

class SurfSpots {
    constructor() {
    this.windSpeed = [-1.3, 1.34, 2.51, -2.55],
    this.totalWindSpeed = 0
  }
            expert(totalWindSpeed) {
            if (totalWindSpeed.some(num => num < 0) === false) {
              return expertSurfLevel.push(this.coords);
            }
          }
          novice(totalWindSpeed) {
            if (totalWindSpeed >= -5 || totalWindSpeed <= 15) {
              return noviceSurfLevel.push(this.coords);
            }
          }
          intermediate(totalWindSpeed) {
            if (totalWindSpeed >= 5 || totalWindSpeed <= 20) {
              return IntermediateSurfLevel.push(this.coords);
            }
          }
}

var surfSpot = new SurfSpots();
surfSpot.expert(surfSpot.windSpeed).novice(surfSpot.totalWindSpeed).intermediate(surfSpot.totalWindSpeed)
console.log("surfSpot",surfSpot)

我已添加 Jfiddle

push returns数组的新长度,这不是你想要的。 Return 实例 (this) 改为:

var expertSurfLevel = []
var noviceSurfLevel = []
var IntermediateSurfLevel = []

class SurfSpots {
  constructor() {
    this.windSpeed = [-1.3, 1.34, 2.51, -2.55],
      this.totalWindSpeed = 0
  }
  expert(totalWindSpeed) {
    if (totalWindSpeed.some(num => num < 0) === false) {
      expertSurfLevel.push(this.coords);
    }
    return this;
  }
  novice(totalWindSpeed) {
    if (totalWindSpeed >= -5 || totalWindSpeed <= 15) {
      noviceSurfLevel.push(this.coords);
    }
    return this;
  }
  intermediate(totalWindSpeed) {
    if (totalWindSpeed >= 5 || totalWindSpeed <= 20) {
      IntermediateSurfLevel.push(this.coords);
    }
    return this;
  }
}

var surfSpot = new SurfSpots();
surfSpot
  .expert(surfSpot.windSpeed)
  .novice(surfSpot.totalWindSpeed)
  .intermediate(surfSpot.totalWindSpeed)
console.log("surfSpot", surfSpot)

不过,实例改变独立的外部变量有点奇怪 - 考虑改变实例变量(例如,在构造函数中创建 this.expertSurfLevel 等,然后推送给它),或者如果你想要在所有实例之间共享的数组,然后使用静态 属性(例如 SurfSpots.expertSurfLevel = [])。