[英]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.