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

时间:2019-07-06 10:51:14

标签: javascript object method-chaining

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

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上添加了

1 个答案:

答案 0 :(得分:2)

push返回数组的新长度,这不是您想要的长度。返回实例(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 = [])。