简体   繁体   English

使用点符号访问 class 或 object 之外的 object 属性?

[英]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..我在我的代码中创建了具有 x、y 和 z 参数的类和函数。

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..但我无法使用任何东西访问 class 之外的任何值,例如......

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.我已经尝试在函数和类上使用这种点表示法,但没有任何效果,如果我将控制台日志放在 class 中,例如只有 (x),我只能记录值。

Please could someone elaborate on how I would be able to use the example of ship.x - enemy.x to access those properties.请有人详细说明我将如何使用 ship.x -enemy.x 的示例来访问这些属性。

Thanks谢谢

You should use the keyword new to create an instance of your your class soo the constructor gets executed.您应该使用关键字 new 来创建 class 的实例,这样构造函数就会被执行。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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