这是我的类Bird
的一部分:
class Bird
{
constructor()
{
this.imagePaths = ['./assets/Bill-Gates.png', './assets/steve-jobs.png', './assets/zuckerberg.png'];
this.elementImg.src = this.changeImage();
this.speed = Math.floor((Math.random() * 5) + 5);
}
在类的构造函数中,我想对不同的速度使用react并为对象分配不同的图像:
changeImage = () => {
if (this.speed < 6) {
return this.imagePaths[0];
}
else if (this.speed < 9) {
return this.imagePaths[1];
}
else if (this.speed > 9) {
return this.imagePaths[2];
}
}
我尝试通过一种方法将图像分配给 elementImg.src
属性来实现此目的。但该方法没有返回所需的值。为什么?
最佳答案
在类中,函数如下所示:
changeImage(){
if (this.speed < 6) {
return this.imagePaths[0];
} else if (this.speed < 9) {
return this.imagePaths[1];
} else if (this.speed > 9) {
return this.imagePaths[2];
}
}
如果这是个问题?
这是应该有效的完整代码。
class Bird {
constructor() {
this.imagePaths = ['./assets/Bill-Gates.png', './assets/steve-jobs.png', './assets/zuckerberg.png'];
this.speed = Math.floor((Math.random() * 5) + 5);
this.elementImg.src = this.changeImage();
}
changeImage(){
if (this.speed < 6) {
return this.imagePaths[0];
} else if (this.speed < 9) {
return this.imagePaths[1];
} else if (this.speed > 9) {
return this.imagePaths[2];
}
}
}
关于javascript - 为什么我的类的构造函数中调用的方法没有按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52687913/