简体   繁体   中英

How access class/Object inside function in javascript?

Here I want to get and set the carbrand with in the function, but it throws error as:

myscript.js:79 Uncaught ReferenceError: Cannot access 'Cars' before initialization
at getCarsInfo (myscript.js:79)
at HTMLButtonElement.onclick (ClassWithGetterAndSetter.html:9)**
class Cars{
    constructor(brand)
    {
        this.carBrand=brand;
    }
    get carBrandName()
    {
        return this.carBrand;
    }
    set carBrandName(newCarName)
    {
        this.carBrand=newCarName;
    }
}


function getCarsInfo()
{
   mycar=new Cars("Tata");
    console.log("Hi ");
    mycar.carBrandName("abc");
   mycar.carBrandName(document.getElementById("getCarName").value);
   console.log(mycar.carBrand)
   document.getElementById("carDetails").innerHTML=mycar.carBrand;
}

Whether the code you've shown will have that error depends on when you call getCarsInfo . If you have

getCarsInfo();

class Cars {
    // ...
}

function getCarsInfo() {
    // ...
}

you'll get that error, because Cars isn't given its value until it's reached in the step-by-step execution of the code (until then it's in the Temporal Dead Zone).

But if you do:

class Cars {
    // ...
}

getCarsInfo();

function getCarsInfo() {
    // ...
}

or

class Cars {
    // ...
}

function getCarsInfo() {
    // ...
}

getCarsInfo();

or

function getCarsInfo() {
    // ...
}

class Cars {
    // ...
}

getCarsInfo();

it will work, because Cars is initialized by the time getCarsInfo tries to use it.


Side note: You use accessor properties like your carBrandName as properties , not as methods:

myCar.carBrandName = "...";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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