开发者

How to create a javascript object within an object?

For example:

function userObject(start_value) {  
    this.name = start_value;
    this.address = start_value;
    this.cars = function() {
        this.value = start_value;
        this.count = start_value;
    };
}

Obviously the above dosent work but would appreciate the direction to take t开发者_运维百科o have cars available as: userObject.cars.value = 100000;

Cheers!


Remember that functions (and thus "object definitions") can be nested (there is absolutely no requirement that this is nested, but having it nested here allows a closure over start_value):

function userObject(start_value) {  
    this.name = start_value;
    this.address = start_value;
    function subObject () {
        this.value = start_value;
        this.count = start_value;
    }
    this.cars = new subObject();
}

However, I would likely opt for this (just create a new "plain" Object):

function userObject(start_value) {  
    this.name = start_value;
    this.address = start_value;
    this.cars = {
        value: start_value,
        count: start_value
    };
}

Happy coding.


so simple anser is to use the object syntax

function userObject(start_value) {  
 this.name = start_value;
 this.address = start_value;
 this.cars = {
  value: start_value,
  count: start_value
 };
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜