繁体   English   中英

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

[英]Accessing object properties outside of class or object using dot notation?

所以这可能很简单,我可能理解错了..

我在我的代码中创建了具有 x、y 和 z 参数的类和函数。

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

我见过这样使用的代码-

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

但我无法使用任何东西访问 class 之外的任何值,例如......

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

它总是说未定义或不起作用。 我已经尝试在函数和类上使用这种点表示法,但没有任何效果,如果我将控制台日志放在 class 中,例如只有 (x),我只能记录值。

请有人详细说明我将如何使用 ship.x -enemy.x 的示例来访问这些属性。

谢谢

您应该使用关键字 new 来创建 class 的实例,这样构造函数就会被执行。 然后您可以使用点符号来访问它,例如:

               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