2015-03-02 58 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 
};