javascript - Calling constructor functions dynamically -


this question has answer here:

i'm looking call constructor function dynamically based on value have in object.

let's have object:

var food = {    pizzas:[     {       pizza: 'pepperoni'     },     {       pizza: 'vegetarian'     }   ]  } 

now, let's have couple of constructor functions bound global object.

window.pizzaconstructors.pepperoni = function(){   // }  window.pizzaconstructors.vegetarian = function(){   // else } 

what want able cycle through food.pizzas array , call corresponding constructor function based on type of pizza of current index.

so, if have:

(for pizza in food.pizzas){   var currentpizza = food.pizzas[pizza]    new pizzaconstructors.currentpizza();  } 

any idea how can go this?

use [] syntax access constructors.

(for pizza in food.pizzas){   var currentpizza = food.pizzas[pizza]    new pizzaconstructors[currentpizza]();  } 

this new pizzaconstructors.currentpizza() means call named currentpizza function.

this new pizzaconstructors[currentpizza.pizza]() means evaluate currentpizza, it's value, call function named of evaluated currentpizza.

var food = {    pizzas:[      {        pizza: 'pepperoni'      },      {        pizza: 'vegetarian'      }    ]  };    const pizzaconstructors = {};    pizzaconstructors.pepperoni = function(){};  pizzaconstructors.vegetarian = function(){};    const arrofobjects = [];    (pizza in food.pizzas) {    const currentpizza = food.pizzas[pizza].pizza;      arrofobjects.push(new pizzaconstructors[currentpizza]());   }    console.log(arrofobjects);


Comments

Popular posts from this blog

Sort a complex associative array in PHP -

vb.net - How to ignore if a cell is empty nothing -

recursion - Can every recursive algorithm be improved with dynamic programming? -