Christoph Pohl Christoph Pohl - 6 months ago 24
Javascript Question

JavaScript: Cannot set property of undefined

I'm pretty new to JS and I'm trying to wrap my head around the object topic in JS.
What I'm trying to do is to set a property of an object prototype to an uninitialized array, so that I can later add multiple objects to that array (for instances of the prototype object)
My code looks like this so far:

function cocktail(){
this.prototype.ingredients = [];
this.printIngredients = function() {
var i;
for (i = 0; i<this.ingredients.length; ++i) {
console.log(this.ingredients.fluid);
console.log(this.ingredients.amount);
}
}
}

var Mojito = new cocktail();
Mojito.ingredients.push({"fluid":"White Rum", "amount":0.05});
Mojito.printIngredients();


That throws:


TypeError: Cannot set property 'ingredients' of undefined


If I change my code into :


this.ingredients = [];


it works but the printIngredients() method prints undefined twice. When I do:

var array = [];
array.push({"a":1, "b":2});
console.log(array[0].a, array[0].b)


everything works as I would expect it to. Can someone clarify what I'm doing wrong and where my thoughts got mixed up?

Answer

Change your code to

function cocktail(){
this.ingredients = []; //this doesn't have prototype property
this.printIngredients = function() {
    var i;
    for (i = 0; i<this.ingredients.length; ++i) {
        console.log(this.ingredients[i].fluid);//use the counter variable to get the fluid value at current counter value 
        console.log(this.ingredients[i].amount);//use the counter variable to get the amount value at current counter value 
        }
    }
}

var Mojito = new cocktail();
console.log(Mojito.ingredients)
Mojito.ingredients.push({"fluid":"White Rum", "amount":0.05});
Mojito.printIngredients();
Comments