簡體   English   中英

初始化前無法訪問“rainDrop”

[英]Cannot access 'rainDrop' before Initialization

我正在使用類和面向對象的編程(我不習慣)在 Sublime Text 中創建一個 Purple Rain Sim。 當我嘗試在下面的代碼中創建新的 object 時,我的 chrome 控制台會拋出錯誤“初始化前無法訪問 'rainDrop'”。 'rainDrop' 是一個創建雨滴對象的 class。 The rainDrop class is in the same.html file as the function, and the rainDrop class is coded before the function code.

這是雨滴 class:

class rainDrop {
    constructor(x, yV, color) {
        this.x = x;
        this.y = 0 - rainH;
        this.yV = yV;
        this.color = color;
    }
}

這個 function 拋出錯誤:

function create_rain_drop() {
    var x = Math.floor(Math.random() * canvasHeight);
    var yV = Math.floor(Math.random() * 5);
    var alpha = Math.random();
    var color = "rgb(148,0,211," + alpha + ")";
    new rainDrop(x, yV, color); // This line throws the error
// I don't believe the arguments in the function are throwing the error
}

為什么會拋出這個錯誤? 先感謝您。

ES6 類在提升時沒有初始化,所以如果你在它之前的 function 中使用它,它會拋出錯誤,所以你可以使用 function 表達式

class RainDrop {
    constructor(x, yV, color) {
        this.x = x;
        this.y = 0 - rainH;
        this.yV = yV;
        this.color = color;
    }
}

const create_rain_drop = () =>{
    var x = Math.floor(Math.random() * canvasHeight);
    var yV = Math.floor(Math.random() * 5);
    var alpha = Math.random();
    var color = "rgb(148,0,211," + alpha + ")";
    new RainDrop(x, yV, color);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM