Aj96
Aj96

Reputation: 187

How to add an array to an object in JavaScript?

I am trying to add the array named ingredients to the object named addIngredients so that when the method displayRecipe() is called it will display both the myFavoriteRecipe() object and also the array by showing it in the console window. I am getting an error message saying displayRecipe() is not defined. Why and how can I fix this?

var ingredients = [];

function myFavoriteRecipe() {
    "use strict";
     this.title = "guacamole";
     this.serves = 8;
    
}

function addIngredients(items) {
    "use strict";
    //CREATING INSTANCE
    var foodItems = new myFavoriteRecipe ();
    //Pushing ingredients to food items
    ingredients.push(foodItems);
    return items;
}

addIngredients("3 Avocados");
addIngredients("1 Lime");
addIngredients("1 TSP salt");
addIngredients("1/2 Cup Onion");
addIngredients("3 Tablespoons of Cilantro");
addIngredients("2 Diced Tomatoes");
addIngredients("1 pinch Ground Pepper");

addIngredients.prototype.displayRecipe = function() {
    "use strict";
    for (var items in addIngredients) {
        return addIngredients[items];
    }
}
  
window.console.log(displayRecipe());

Upvotes: 1

Views: 76

Answers (1)

Miroslav Glamuzina
Miroslav Glamuzina

Reputation: 4557

The prototype should be set on myFavoriteRecipe, not on addIngredients.

Please take a look at this:

function myFavoriteRecipe(info) {
  this.title = info.title || 'Not Set';
  this.serves = info.serves || 0;
  this.ingredients = [];
  this.addIngredients = function(items) {
    this.ingredients.push(items);
  };
}
myFavoriteRecipe.prototype.displayRecipe = function() {
  return this.ingredients;
}

let recipe = new myFavoriteRecipe({
  title: 'guacamole',
  serves: 8
});
recipe.addIngredients("3 Avocados");
recipe.addIngredients("1 Lime");
recipe.addIngredients("1 TSP salt");
recipe.addIngredients("1/2 Cup Onion");
recipe.addIngredients("3 Tablespoons of Cilantro");
recipe.addIngredients("2 Diced Tomatoes");
recipe.addIngredients("1 pinch Ground Pepper");

console.log(recipe.displayRecipe());

Hope this helps,

Upvotes: 1

Related Questions