定义返回 'undefined' 的对象的属性

Defining properties of an object returning 'undefined'

我正在尝试创建一个主对象来保存我的程序的数据,如下所示:

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 对象的属性 w/in state 对象:

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

当我这样测试函数时:

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

它returns'undefined.'

不知道为什么。

该函数 return 没有任何作用。其实就是运行函数成功了。但是因为您没有 return 语句,所以 return 值将是 undefined.

要更改它,请在您的函数中添加 return 语句。

你的函数 manufacturingInfo 没有 return 东西,所以调用的值是 undefined,但是它确实对 state,所以也许你真的想

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

您希望它达到什么效果 return?

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