ฉันจะใช้คลาส js ของฉันในฟังก์ชัน jQuery ได้อย่างไร

ฉันสร้างชั้นเรียนของฉัน

export default class Quiz{
    constructor() {
        this.quizWrapper = null;
        this.quizStage = null;
        this.progressed = 1;
        this.quizType = 'empty';
        this.scope = 0;
    }
    start(){
        this.scope= 1;
        return true;
    }
};

และนำเข้าด้วย

// let test = new Quiz();
// console.log(test); // --> reurn the class fine 

jQuery(document).ready(function ($) {
    var test = new Quiz();
    console.log(test.start()); // --> reurn true
}); 

ไม่เป็นไร แต่ถ้าฉันเรียก test ในคอนโซลของเบราว์เซอร์ ฉันเห็นข้อผิดพลาด Uncaught ReferenceError: test is not specified

ถ้าฉันทำสิ่งนี้:

jQuery(document).ready(function ($) {
    $.test = new Quiz();

ฉันสามารถใช้กับ $.test ในคอนโซลของเบราว์เซอร์ได้

ใครช่วยอธิบายให้ฉันฟังหน่อยได้ไหมว่าทำไมถึงเป็นเช่นนั้น? ฉันต้องการเริ่มต้นโมดูลของฉันหลังจากโหลดสคริปต์จาก jQuery และใช้งาน


person Jury Dpling    schedule 23.10.2019    source แหล่งที่มา


คำตอบ (1)


เป็นเพราะคุณกำลังกำหนด test ภายในฟังก์ชัน ดังนั้นจึงไม่ได้แนบไปกับขอบเขตส่วนกลาง

person Grammy    schedule 23.10.2019