2015-03-02 54 views
0

我試圖創建一個主對象,會認爲像這樣我的程序中的數據:定義屬性回報「未定義」

var state; 
var init = function() { 
    state = { 
     runInfo: { //object that'll hold manufacturing info - run, desired price, servings/container 
      price: null, 
      containers: null, 
      servings: null 
     }, 
     formula: [], 
     totalsServing: [], 
     totalsBottle: [], 
     totalsRun: [] 
    }; 
}; 

我試圖設置屬性所述runInfo物體的重量/在用下面的函數的狀態對象:

manufacturingInfo = function(price, containers, servings) { 
     state.runInfo.price = price; 
     state.runInfo.containers = containers; 
     state.runInfo.servings = servings; 
}; 

當我測試像這樣的功能:

init(); 
console.log(manufacturingInfo(10, 500, 30)); 

它返回「未定義」。

不知道爲什麼。

+0

您需要在'manufacturingInfo'內有一個['return'語句](http://www.ecma-international.org/ecma-262/5.1/#sec-12.9)。 – Oriol 2015-03-02 15:33:13

+0

你想調用這個方法嗎?它沒有回報價值。你是否試圖使用該方法構造一個對象?你還沒有使用'new'關鍵字。 – Sam 2015-03-02 15:33:23

回答

2

你的功能manufacturingInforeturn東西,所以調用的值是不確定,但它確實更改state,所以也許你真的想

init(); 
manufacturingInfo(10, 500, 30); 
console.log(state); 
0

該函數不返回任何東西。實際上它正在成功運行該功能。但是因爲您沒有返回聲明,所以返回值將爲undefined

要更改該語句,請在函數中添加return語句。

0

你怎麼指望它返回?

manufacturingInfo = function(price, containers, servings) { 
    state.runInfo.price = price; 
    state.runInfo.containers = containers; 
    state.runInfo.servings = servings; 


    return state.runInfo; // anything here you want the function to report 
};