javascript - 如何在面向对象的 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)
解决方案
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 = []
)。
推荐阅读
- string - 如何在循环中显示两个字符串数组中的不同元素?
- angular - Angular 检测何时发送请求并在 Angular 6 中完成
- python - Python:list() 函数弄乱了 map()
- css - 一个滑入和一个滑出的元素如何在同一“水平”上?
- asp.net - 在 asp 中继器中使用 bootstrap-4-carousel
- reactjs - 反应组件状态未通过回调更新
- excel - VBA将参数从函数传递给子
- rstudio - 为什么在使用 Mosaic 包中的 plotFun 时 RStudio 会出错?
- r - 如何有效地将 dpoibin 分解为 R 中的和数?
- android - 在依赖项中添加 Volley