2011-05-20 132 views
1

例如:如何在一個對象內創建一個javascript對象?

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

顯然上述dosent工作但希望的方向取爲具有可作爲汽車: userObject.cars.value = 100000;

乾杯!

回答

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 
    }; 
} 

快樂編碼。

+0

this.cars = { 值:START_VALUE, 計數:START_VALUE }; 做到了。謝謝。 – Ernest 2011-05-20 05:19:40

1

如此簡單雁是使用對象語法

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