简体   繁体   中英

Accessing object properties outside of class or object using dot notation?

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM