Challenge: Solution Review

This lesson will explain the solution to the problem from the previous coding challenge.

We'll cover the following...

Solution #

Press + to interact
function ToyFactory() {
this.toy = ToyDuck;
this.createToy = function(toyChosen) {
if (toyChosen.toyType == "duck") {
this.toy = ToyDuck;
} else if (toyChosen.toyType == "car") {
this.toy = ToyCar;
}
return new this.toy(toyChosen);
}
}
function ToyDuck(toyObj) {
this.color = toyObj.color;
this.price = toyObj.price;
}
function ToyCar(toyObj) {
this.color = toyObj.color;
this.price = toyObj.price;
this.name = toyObj.name;
}
var toyFactory = new ToyFactory();
var car = toyFactory.createToy({
toyType: "car",
color: "blue",
price: 12,
name: "honda"
})
var car = toyFactory.createToy({
toyType: "car",
color: "blue",
price: 12,
name: "honda"
})
console.log(car)
console.log(car instanceof ToyCar)
var duck = toyFactory.createToy({
toyType: "duck",
color: "yellow",
price: 5,
})
console.log(duck)
console.log(duck instanceof ToyDuck)

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.

  • ToyDuck

    function ToyDuck(toyObj){
      this.color = toyObj.color;
      this.price = toyObj.price;
    }
    

    It accepts a parameter toyObj, that is, the “toy object”, sets its color equal to toyObj.color and its price equal to toyObj.price.

  • ToyCar

    function ToyCar(toyObj){
    
...