0

So this may be simple and I'm probably understanding this wrong..

I have created both classes and functions in my code that have the parameters of x, y and z as such..

class Example {
constructor(x, y, z) {
    this.x = x;
    this.y = y;
    this.z = z;
...}
Example(123, 456, 789);

I have seen code being used such as this -

if (Math.hypot(ship.x - enemy.x, ship.y - enemy.y [....] 

But i cannot access any of the values outside of the class using anything such as..

console.log(Example.x);
if (Example.x > 1){ console.log('something here');

It always just says undefined or just doesnt work. I have tried using this dot notation on functions and classes but nothing works, I can only log the values if i place the console log inside the class with just (x) for example.

Please could someone elaborate on how I would be able to use the example of ship.x - enemy.x to access those properties.

Thanks

Hakaewt
  • 49
  • 1
  • 7
  • 3
    `let example = new Example(123, 456, 678)`? – jonrsharpe Apr 30 '20 at 20:20
  • @jonrsharpe okay cool that works - however I am creating new instances into an array and having multiple random generated values as the x,y,z. Do you know how i can log the value of the example.x inside of the array? like so - exampleArray[i] = new Example(1, 2, 3). Thanks – Hakaewt Apr 30 '20 at 20:33
  • 1
    I would recommend running through some structured JavaScript tutorials. – jonrsharpe Apr 30 '20 at 20:33
  • @Hakaewt By accessing the `.x` property on the `exampleArray[i]` instance. – Bergi Apr 30 '20 at 21:59

1 Answers1

0

You should use the keyword new to create an instance of your your class soo the constructor gets executed. Then you can use the dot notation to access it for example:

               class Example {
               constructor(x, y, z) {
                this.x = x;
                this.y = y;
                this.z = z;
                }
                var exp = new Example(123, 465, 789);
                 console.log(exp.x);
Aku Bagwan
  • 13
  • 2
  • Thanks! I am creating new instances into an array and having multiple random generated values as the x,y,z. Do you know how i can log the value of the example.x inside of the array? like so - exampleArray[i] = new Example(1, 2, 3) ? – Hakaewt Apr 30 '20 at 20:52