Accessing class methods

Hi,

I’m new to javascript so I’m not familiar with classes in javascript (I’m from Java). I declared a class like so:

class Obj {
	constructor(name, distance, description, colour, size) {
		//constructor
	}

	draw() {
		//stuff
	}
}

And then in the sketch’s draw method I attempt to call an Obj instance’s draw method:

function draw() {
     object.draw();
}

But I get the error:

Uncaught TypeError: object.draw is not a function

What am I doing wrong here? Thanks for reading.

1 Like

I can’t pinpoint anything wrong from your incomplete posted code. :expressionless:
But you can check out these 2 sketches below that use class: :innocent:

OpenProcessing.org/sketch/717760#code


1 Like

My code is a bit long so I didn’t want to paste it, here is the link to my sketch

1 Like

objects.push(new Object("Sun", 0, "description", color(255, 204, 0), 500));

Your class is called Obj, not Object, which is btW a JS builtin constructor:

objects.push(new Obj("Sun", 0, "description", color(255, 204, 0), 500));


You’re using for...in here: for (let object in objects) {

Use for...of instead: for (const object of objects) {


P.S.: It’s advisable to load assets within preload():
p5js.org/reference/#/p5/preload


2 Likes

-a-

	objects.push(new Obj("Sun", 0, "description", color(255, 204, 0), 500));

not new Object()

-b-

	for ( let i =0; i < objects.length; i++) objects[i].draw();

works well

1 Like

@GoToLoop thank you for the comprehensive reply!

@kll Can’t believe I didn’t realize that I forgot to change the class name there … :man_facepalming:

2 Likes