1

I want to display an image and the according text from an object chosen randomly from an array.

Basically that's the chain I plan on using to get both the name and the image: ingredient <- ingredientArray <- getRandomIngredient <- getIngredientImage (& getIngredientName)

I'm sure there is something basic I just don't get about object oriented programming, but I can't get it to work.

ingredientArray:

const ingredient1 = new Ingredient("green salad", require('./app/components/img/base/green_salad.jpg'));
const ingredient2 = new Ingredient("mixed salad", require('./app/components/img/base/mixed_salad.jpg'));
var ingredientArray = ["ingredient1", "ingredient2"]

getRandomIngredient:

function getRandomIngredient (arr){
  if (arr && arr.length) {
    return arr[Math.floor(Math.random() * arr.length)];
  }
}

class Ingredient:

function Ingredient (ingredientName, ingredientImage){
  this.ingredientName = ingredientName;
  this.ingredientImage = ingredientImage;

  Ingredient.prototype.getIngredientName = function(){
    return this.ingredientName;
  }

  Ingredient.prototype.getIngredientImage = function(){
    return this.ingredientImage;
  }
}

What I would like to do:

<Image source = {getRandomIngredient(ingredientArray).getIngredientImage()}

But I get the following error message:

TypeError: getRandomIngredient(...).getIngredientImage is not a function

If I call the function getIngredientImage() directly, I get a working result:

<Image source = {base1.getIngredientImage()} />
2
  • Can you post your entire component JS file? Commented Feb 26, 2019 at 18:27
  • To mark a question as solved, one does not need to edit the title on Stack Overflow - there is a proper acceptance system. Click the tick/check mark adjacent to the answer you liked most. It is not mandatory, but it is nice, as it encourages helpful people to help again. Commented Feb 26, 2019 at 21:25

2 Answers 2

1

There's no getIngredientImage method because getRandomIngredient(ingredientArray) doesn't return an instance of Ingredient. Because ingredientArray is an array of strings, not Ingredient instances.

It should be:

var ingredientArray = [ingredient1, ingredient2]
Sign up to request clarification or add additional context in comments.

Comments

0

Try adding the variables to your "ingredientArray" instead of the "string" identifiers that you are using for your constants. IE change

var ingredientArray = ["ingredient1", "ingredient2"]

to

var ingredientArray = [ingredient1, ingredient2]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.