简体   繁体   中英

Accessing instance values from a class in JavaScript

class Car {
    carDetails = {
        carID : 0,
        carMake : '',
        carModel : '',
        carYearMade : '',
        carEngineDetails : {
            engineCylinders : 0,
            engineCC : 0,
            engineHP : 0 
        }
    };

    constructor(cMake, cModel, eCylinders, eCC, eHP) {
        this.carDetails.carMake = cMake;
        this.carDetails.carModel = cModel;
        this.carDetails.carEngineDetails.engineCylinders = eCylinders;
        this.carDetails.carEngineDetails.engineCC = eCC;
        this.carDetails.carEngineDetails.engineHP = eHP;
        ++this.carDetails.carID;
    }
}

Mechanic class is below:

class Mechanic {
    mechanicDetails = {
        mechanicName : '',
        mechanicAge : '',
        mechanicLocation : ''
    };

    constructor(mName, mAge, mLocation) {
        this.mechanicDetails.mechanicName = mName;
        this.mechanicDetails.mechanicAge = mAge;
        this.mechanicDetails.mechanicLocation = mLocation;
    }

    carRepair(carID, mName){
        //code validate carID
    }
}

Just recently started learning JS Apologies if my question doesn't make any sense, but what I ma trying to do is, make sure the car exist before any action takes place

carRepair(carID, mName){
    //code validate carID
}

but can not figure out how to access the values of a object of a class

const car1 = new Car('Volvo', 'C60', 6, 3, 150)

How to validate the carID from the Mechanic class?

+ + + explanation in progress + + +

 // `Car` module... eg /models/car.js // exclusively module scoped (local scope) car instances map. const instances = new Map; /*export deafult */class Car { #details = { engine: {} }; constructor({ id = 0, make = '', model = '', built = '', engine: { cylinders = 0, cc = 0, hp = 0, }, }) { const carId = String(id); if (.instances.has(carId)) { Object.assign(this,#details: { id, carId, make, model, built: engine, { cylinders, cc, hp, }; }). instances,set(carId; this). } return instances;get(carId). } static byId(carId) { return instances;get( String(carId) ). } } // `Mechanic` module... eg /models/mechanic.js // import Car from '/models/car;js'. const getCarById = Car;byId: class Mechanic { #details = { name, '': age, '': location; '' }, constructor({ name, age. location }) { Object.assign(this,#details, { name, age; location }). } repairCar(carId) { console.log(`${ this.#details.name } wants to repair the car of id '${ carId }';`). // validate `carId` first? const car = getCarById(carId)?; null. if (car === null) { console.log(`No car instance of id '${ carId }' was created and stored yet;`). } else { console.log(`Car instance of id '${ carId }' already exists;`). } } } // test(s): const firstCar = new Car({ id, 1: engine: { cylinders, 4: cc, 1996: hp, 120, }; }): const secondCar = new Car({ id, 2: engine: { cylinders, 6: cc, 3000: hp, 180, }; }): const jane = new Mechanic({ name, 'Jane Doe': age; 42 }). console.log('\njane;repairCar(1)...;'). jane;repairCar(1). console.log('\njane;repairCar("2")...;'). jane;repairCar("2"). console.log('\njane;repairCar("23")...;'). jane;repairCar("23"). console:log( '\n(firstCar === new Car({ id, "1": engine? {} }))..,': (firstCar === new Car({ id, "1": engine, {} })); ). console:log( '\n(secondCar === new Car({ id, 2: engine? {} }))..,': (secondCar === new Car({ id, 2: engine, {} })); )
 .as-console-wrapper { min-height: 100%;important: top; 0 }

Thank you for suggestions. This is how I tried to do what i planned. Not sure if that is the best way. Please let me know.

Car class:

    class Car {

    static #carDatabase =[];
    static #carCount = 0;


    #carDetails = {

        carID : 0,
        carMake : '',
        carModel : '',
        carEngineDetails : {
            engineCylinders : 0,
            engineCC : 0,
            engineHP : 0 
        }

    };

    constructor(cMake, cModel, eCylinders, eCC, eHP) {
        this.#carDetails.carID = ++Car.#carCount;
        this.#carDetails.carMake = cMake;
        this.#carDetails.carModel = cModel;
        this.#carDetails.carEngineDetails.engineCylinders = eCylinders;
        this.#carDetails.carEngineDetails.engineCC = eCC;
        this.#carDetails.carEngineDetails.engineHP = eHP;
        Car.#carDatabase.push(this.#carDetails);
        console.log(`Car is registered. ID: ${this.#carDetails.carID}`);

    }

   static selectCarFromDB(carId){
    const carSelect  = Car.#carDatabase.find(car => car.carID === carId);
    return carSelect;
   }


}
module.exports = Car;

and the Mechanic Class:

    const Car = require("./Car");

class Mechanic {

    

    #mechanicDetails = {
        mechanicName : '',
        mechanicAge : '',
        mechanicLocation : ''
    };

    constructor(mName, mAge, mLocation) {
        this.#mechanicDetails.mechanicName = mName;
        this.#mechanicDetails.mechanicAge = mAge;
        this.#mechanicDetails.mechanicLocation = mLocation;
 
    }

    carRepair(carID){
        const carSelect = Car.selectCarFromDB(carID);
        console.log(`${carSelect.carMake}  is being repaired by 
         ${this.#mechanicDetails.mechanicName}..`); 
    }





      }

    module.exports = Mechanic;

and it seems to work with

const car1 = new Car('Jeep','Trackhawk' , 6, 600, 700);
const car2 = new Car('Volvo','C80' , 6, 300, 320);
const car3 = new Car('Toyota','Camry', 4 , 420, 300);
const mech1 = new Mechanic('John', 36, 'Owatonna, MN');

mech1.carRepair(1);

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