JavaScript: style.width=this.width+"px"; is not working

I’m new to JavaScript.
I’m learning Dom and OOP recently. I’m working on a Snake game project now.

I’m trying to use Food.init to create a cube (width: 20px, height:20px) inside .map, But when I use “style.width=this.width+“px”;” to set width, it’s not working!

Please give me some advice about how to solve it.
here is my code:

Hello @ArinWu, and welcome back to the forum

Apologies if this doesn’t help, I don’t understand your issue 100%, but consider the values you are passing to the function:

var fd = new Food("20px", "20px", "red");

And then consider how these values are used in the init function:

cube.style.width = this.width + "px";
cube.style.height = this.height + "px";

You might notice that the value assigned to the properties is not a valid length.

It might also help to log this specific value.

console.log(this.width + "px");

Let me know if this is enough or a hint, or if your issue is with another part of the code altogether.

1 Like

Thank you so much!
I’m sorry about my expression, I will try to correct.
Your answer is very helpful! The problem is “when this.width is already 20px, if I put this.width + “px”, it will become unnable to set width”.