Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

calling object literal methods

Hi, as a small project, I'm trying to build an online shop using only html, css and javascript. The code below is to create a new Item (class Item on a different script) and add it to the stock array. I'm new to OOJS, and when I run this code, I'm getting "Uncaught TypeError: createNewItem is not defined". I think there is a core concept here I'm not understanding. Help much appreciated!

const store = {
    stock : [],

    createNewItem: function(name, description, itemNo, size, price, imgURL){
        const newItem = new Item(name, description, itemNo, size, price, imgURL);
        return newItem;
    },

    addItemToStock: function() {
        this.stock.push(this.newItem);
        console.log(`${item} added to stock`);
        console.log(this.stock);
    },
}

createNewItem('fluffy jumper', 'rib roll pink', 004, 'S', 55, '../img/samples/img4.jpg');
addItemToStock();

1 Answer

Since you have 'createNewItem' as a method inside of the store object it would be called like this:

store.createNewItem('fluffy jumper', 'rib roll pink', 004, 'S', 55, '../img/samples/img4.jpg');

Also this.newItem will be undefined in the 'addItemToStock' method unless it is stored on the store object:

const store = {
    stock : [],
    newItem: {},
    createNewItem: function(name, description, itemNo, size, price, imgURL){
        this.newItem = new Item(name, description, itemNo, size, price, imgURL);
    },

    addItemToStock: function() {
        this.stock.push(this.newItem);
        console.log(`${this.newItem.name} added to stock`);
        console.log(this.stock);
    },
}

store.createNewItem('fluffy jumper', 'rib roll pink', 004, 'S', 55, '../img/samples/img4.jpg');
store.addItemToStock();

Perfect, thanks so much for your help!