this.y 未定义,即使它是明确的

问题描述 投票:0回答:1

我一直在关注这个 youtube 教程(https://www.youtube.com/watch?v=vyqbNFMDRGQ)并且我遇到了一个问题,当我尝试设置 this.position 以使用 this.velocity 进行更新时,它会返回 类似未捕获类型错误第 33 行的错误:无法读取未定义的 this.velocity.y 的属性

我尝试过 console.log(this.velocity.y) 但不起作用,为什么它没有定义?

如果你们中有人的话。可以帮忙那就太好了

这是我的代码,错误行上突出显示:

const canvas = document.querySelector('canvas')
const c = canvas.getContext('2d')

canvas.width = 1024
canvas.height = 576

c.fillRect(0, 0, canvas.width, canvas.height)

class Sprite {

    constructor({ position, velocity }) {

        this.position = position

        this.velocity = this.velocity

    }

    draw() {

        c.fillStyle = 'red'

        c.fillRect(this.position.x, this.position.y, 50, 150)

    }

    update() {

        this.draw()


// error here 
        this.position.y += this.position.y;
// error here
    }

}

const player = new Sprite({
    position: {
        x: 0,
        y: 0
    },
    velocity: {
        x: 0,
        y: 10
    }
})


const enemy = new Sprite({
    position: {
        x: 400,
        y: 100
    },
    velocity: {
        x: 0,
        y: 0
    }
})



console.log(player)

function animate() {

    window.requestAnimationFrame(animate)

    console.log('success')

    c.fillStyle = 'black'

    c.fillRect(0, 0, canvas.width, canvas.height)

    player.update()

    enemy.update()

}

animate()

javascript object undefined
1个回答
0
投票

你的问题是因为你的构造函数,你将 this.velocity 分配给 this.velocity 而不是

this.velocity = velocity

© www.soinside.com 2019 - 2024. All rights reserved.