JavaScript对象文字属性范围

时间:2014-01-13 06:24:27

标签: javascript

我正在尝试找到一种方法,将car.engine.name的值提供给manufacturer对象的属性info。我尝试过很少的东西,但我一直都没有定义。

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

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

}

3 个答案:

答案 0 :(得分:1)

关键是让第一个赋值先执行,以便属性存在,然后从现有数据中设置manufacturer属性。

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

答案 1 :(得分:1)

或者,框架不可知:

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

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

答案 2 :(得分:0)

尝试这样的事情

$(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
})