Challenge: Solution Review
Explore the solution to a challenge implementing the factory pattern in JavaScript. Understand how to use constructor functions like ToyDuck and ToyCar within a ToyFactory to create objects based on provided parameters. This lesson helps you apply creational design patterns to efficiently manage object instantiation in coding interviews.
We'll cover the following...
We'll cover the following...
Solution #
Explanation
The task was to create a function createToy, which instantiated either a ToyDuck or a ToyCar object.
We start by defining the constructor functions. Let’s take a look at them.
-
ToyDuckfunction ToyDuck(toyObj){ this.color = toyObj.color; this.price = toyObj.price; }It accepts a parameter
toyObj, that is, the “toy object”, sets itscolorequal totoyObj.colorand itspriceequal totoyObj.price. -
ToyCarfunction