首页 > 解决方案 > 如何在面向对象的 Javascript 中进行方法链接?

问题描述

我正在尝试进行方法链接,但它在第二种方法上返回未定义。我在每个函数中都添加了 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上添加了

标签: javascriptobjectmethod-chaining

解决方案


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 = [])。


推荐阅读