简体   繁体   中英

Defining properties of an object returning 'undefined'

I'm trying to create a master object that'll hold the data for my program that looks like this:

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: []
    };
};

I'm trying to set the properties of the runInfo object w/in the state object with the following function:

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

When I test the function like this:

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

it returns 'undefined.'

Not sure why.

Your function manufacturingInfo does not return something, so the value of the invocation is undefined , however it does make changes to state , so maybe you really wanted to

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

That function doesn't return anything. It is in fact running the function successfully. But because you don't have a return statement the return value will be undefined .

To change that put a return statement in your function.

What do you expect it to 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
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM