javascript - 为什么我的类的构造函数中调用的方法没有按预期工作?

标签 javascript constructor

这是我的类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/

相关文章:

javascript - 使用 .seek() 方法手动控制 Netflix 播放器

javascript - Angular JS 中的 Steam Web API : Issue with the GetAppList JSON and $http. jsonp

python - 仅使用静态方法调用继承类的构造函数

javascript - 使用 Javascript 计算 JSON 嵌套数组中值的重复次数

javascript - 文本在一行上

javascript - 使用 Javascript 解码 Google Oauth2 访问 token

java - 如何强制子类创建构造函数?

templates - 指定了多个复制构造函数

c++ - 为什么 C++ 选择将我的返回值转换为 int?

c++ - 初始化列表 vs 构造函数赋值 vs 变量定义