I'm trying to create an instance of the Object class but i get this error:
Uncaught TypeError: this.canvas is undefined
I'm quite new to javascript, so I might have made a few silly mistakes.
Here is the code and the folder structure:
projectname/
- index.html
- index.js
- js/
-- Object.js
file: index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
<div id="container"></div>
<script src="index.js" type="module"></script>
</body>
</html>
file: index.js
import { Object } from "/js/Object.js";
var obj = new Object();
obj.position = (500, 500, 0);
file: /js/Object.js
export class Object {
constructor() {
this.position = new Array(0, 0, 0);
this.velocity = new Array(0, 0, 0);
this.force = new Array(0, 0, 0);
this.mass = 0;
this.canvas = document.createElement("canvas");
}
get position() {
return this._position;
}
set position(n_position) {
this._position = n_position;
this.canvas.style.left = n_position[0].toString()+"px";
this.canvas.style.top = n_position[1].toString()+"px";
}
}
Inside your constructor you have:
this.position = new Array(0, 0, 0);
which calls the setter function which tries to read this.canvas before you have:
this.canvas = document.createElement("canvas");
which creates the canvas that you tried to modify five lines earlier.
Order matters. Create your canvas before you try to modify it.