如何在对象中创建javascript对象?

时间:2011-05-20 04:55:02

标签: javascript object

例如:

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

显然上面的内容不起作用,但我很欣赏让汽车可用的方向:user Object.car's.value = 100000;

干杯!

2 个答案:

答案 0 :(得分:5)

请记住,函数(以及“对象定义”)可以嵌套(绝对不要求嵌套,但是嵌套在这里允许封闭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();
}

但是,我可能会选择这个(只需创建一个新的“普通”对象):

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

快乐的编码。

答案 1 :(得分:1)

如此简单的答案是使用对象语法

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