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
const Ninja = function(name) {
this.points = 100
this.name = name
}
Ninja.prototype.punch = function(otherNinja) {
if(otherNinja.points > 0 && this.points > 0){
otherNinja.points -= 20
return `${otherNinja.name}'s points are ${otherNinja.points}`
}else{
return `Can't punch ${otherNinja.name}`
}
}
Ninja.prototype.kick = function(otherNinja) {
if(otherNinja.points > 0 && this.points > 0){
otherNinja.points -= 50
return `${otherNinja.name}'s points are ${otherNinja.points}`
}else{
return `Can't kick ${otherNinja.name}`
}
}
const ninja1 = new Ninja("Ninja1")
const ninja2 = new Ninja("Ninja2")
console.log(ninja1.kick(ninja2))
console.log(ninja2.punch(ninja1))
console.log(ninja1.kick(ninja2))
console.log(ninja1.punch(ninja2))
console.log(ninja2.kick(ninja1))

Explanation

In this challenge, you had to create a small game for ninja fighting using the prototype pattern. Two ninjas, ninja1 and ninja2, fight each other in this game. They either have the option to kick or punch. Let’s look at how we achieved this using the prototype pattern.

First, we define the Ninja constructor function. It accepts the name parameter and sets the name property of the current object equal to it. Next, it defines the points property for the instantiated object and ...