简体   繁体   中英

JavaScript object literal property scope

I am trying to find a way to get the value of car.engine.name to the property manufacturer of info object. I have tried few things but i keep getting undefined.

var car = { engine:{} }
car.engine = {

    name : "bmw",
    info : {
        rpm : 5500,
        manufacturer : car.engine.name // undefined
    }

}

Or, framework agnostic:

var Car = function (config) {
    this.engine = {
        name: config.name,
        info: {
            rpm: config.rpm,
            manufacturer: config.name
        }
    }
}

var bmw = new Car({name: 'bmw', rpm: 5500});

Key is to let the first assignment execute first, so that the property exists, and then set the manufacturer property from the existing data.

var car = { engine:{} }
car.engine = {
    name : "bmw",
    info : {
        rpm : 5500
    }
}
car.engine.info.manufacturer = car.engine.name;

try something like this

$(function(){
    var _name = "bmw"
    var car = { engine:{} }
    car.engine = {

        name : _name,
        info : {
            rpm : 5500,
            manufacturer : _name
        }

    }
    console.log(car.engine.name)//bmw
    console.log(car.engine.info.manufacturer)//bmw
})

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