Categories
education JavaScript

Using Monty Python to Explain JavaScript Constructor Functions

Before we begin, let me address the elephant in the room.

Yes, I am using Monty Python to explain a coding concept. No, I am not explaining a Python concept using Monty Python.

Is this a horrible injustice to the world of puns and coding? Is this awfully off-brand for a writer known to make ridiculous coding puns?

Yes and yes. I’m sorry.

Moving on.

Let’s start with the Bridge of Death scene from The Holy Grail.

In this scene, we have three knights: Sir Arthur, Sir Robin, and Sir Galahad. Each has a set of questions they have to answer in order to cross the bridge.

Arthur goes first. The troll asks him three questions: what is his name (“Arthur”), what is his favorite color (“blue”), and what is quest (“to seek the Grail”).

Robin flounders on the second question: “What is your favorite color?” and is flung into the depths below.

Galahad gets the hardest question: “What is the airspeed velocity of an unladen swallow?”

“What kind of swallow?” he asks. The troll doesn’t know — and is flung into the depths below too. Thus ends one of the finest moments in cinematic history.

Let’s turn this scene into JavaScript.

Step 1: Creating our constructor function

Think of a JavaScript constructor function as a cookie cutter, or a blueprint. It’s the tool we use to create objects.

For example: in the bridge scene, we have three knights.

Each knight has the same set of properties— they all have a name, a favorite color, and are asked a third question — but the values of these properties are different for each knight.

A constructor function (i.e., the blueprint) creates a prototype of an object; the new operator creates the object itself, which inherits the properties from the constructor function.

Let’s make an object called Knight using a constructor function.

// 1) Create the Knight object
function Knight(name, favoriteColor, thirdQuestion) { this.name = name;
this.favoriteColor = favoriteColor;
this.thirdQuestion = thirdQuestion;}

Here, the constructor function takes three arguments: namefavoriteColor, and question.

Inside the function are three expressions:

this.name = name;
this.favoriteColor = favoriteColor;
this.question = question;

These expressions create and initialize the properties of the object.

For example, this.name = name creates and initializes the property name to the object Knight. The this keyword allows us to access the name property for any instance of that object. Once the name property is initialized, we can access it just like we would a JavaScript method (using ‘dot’ notation).

A quick note on ‘this’

this is a notoriously tricky topic in JavaScript. We’ll only scratch the surface here, but if you’re curious to learn more, check out this resource from MDN, or this article from Tutorials Teacher.

For our purposes, this refers the object itself (i.e., the individual knight in question). (The tricky part about this is understanding exactly which object it refers to — it can get complicated quickly!)

Let’s use Sir Robin as an example. We’ll create a Knight object called robin.

We can do this using the operator new:

// Creating a Knight objectvar robin = new Knight('Sir Robin', 'Yellow', 'What is the capital of Assyria?');

The statement above creates a Knight object called robin, and assigns its properties the values ‘Sir Robin’, ‘Yellow’, and ‘What is the capital of Assyria?’.

What if we wanted to print Robin’s favorite color? We can use the following expression, accessing the ‘color’ property using dot notation (just like ‘this.color’, but replacing ‘this’ with ‘Robin’):

console.log(robin.favoriteColor);
Output --> "Yellow"

Now, let’s create objects for Sir Arthur and Sir Galahad too. (You know, just so we don’t leave them out.)

// Creating Sir Arthur and Sir Galahad instances using Knight object
var arthur = new Knight('Sir Arthur', 'Blue', 'What is your quest?');var galahad = new Knight('Sir Galahad', 'Green', 'What is the airspeed velocity of an unladen swallow?');

Now, we have three separate objects. And now, it’s time to write a program that plays out the bridge scene.

Here we go, friends.

Putting it all together

Here it is, friends. That same scene — but in JavaScript.

Step 1) Create a basic HTML document with the following elements:

  • An h1 (for our title)
  • An h2 (for our subtitle)
  • Three buttons, each with their own ids
// HTML body
<body>
<h1>Monty Python and the Holy Grail - the Bridge of Death Quiz</h1>
<p>(using JavaScript)</p>
<h2 id="crossMessage">Select Your Knight</h2>
<p></p>
<button id="robin">Sir Robin</button>
<button id="arthur">Sir Arthur</button>
<button id="galahad">Sir Galahad</button>
</body>

Step 2) In a new file, create a JavaScript object for each button (one for each knight).

Here, we’re using the HTML ids we created earlier to create JS objects for each knight’s button.

const robinButton = document.querySelector('#robin');
const arthurButton = document.querySelector('#arthur');
const galahadButton = document.querySelector('#galahad');

Step 3) Create constructor function for ‘Knight’ object

function Knight(name, favoriteColor, thirdQuestion) {

this.name = name;
this.favoriteColor = favoriteColor;
this.thirdQuestion = thirdQuestion;

}

Step 4) Use ‘new’ operator to create objects for each knight

const robin = new Knight('Sir Robin', 'Yellow', 'What is the capital of Assyria?');
const arthur = new Knight('Sir Arthur', 'Blue', 'What is your quest?');
const galahad = new Knight('Sir Galahad', 'Green', 'What is the airspeed velocity of an unladen swallow?');

Step 5) Have user select a knight.

addEventListener('click', function () {}) → This statement is the *chef’s kiss* of the program. It’s what makes our buttons do what we want them to.

In this function, depending on which knight the user selects, we iterate through the questions, and display a pop up note that congratulates the user for successfully crossing the bridge, or sends the user ‘into the abyss’.

// If user clicks 'Sir Robin', iterate through questions
robinButton.addEventListener('click', function () {
let nameQuestion = prompt('What is your name?');
if (nameQuestion != robin.name) {
alert("Wrong! Into the abyss with ye.");
} else {
let colorQuestion = prompt('What is your favorite color?');
if (colorQuestion != robin.favoriteColor) {
alert('Wrong! Into the abyss with ye.');
} else {
let thirdAnswer = prompt(robin.thirdQuestion);
if (thirdAnswer != 'Gondar') {
alert('Wrong! Into the abyss with ye.');
} else {
alert("You may cross the bridge!")
}
}
}
})// If user clicks 'Sir Arthur', iterate through questions
arthurButton.addEventListener('click', function () {
let nameQuestion = prompt('What is your name?');
if (nameQuestion != arthur.name) {
alert("Wrong! Into the abyss with ye.");
} else {
let colorQuestion = prompt('What is your favorite color?');
if (colorQuestion != arthur.favoriteColor) {
alert('Wrong! Into the abyss with ye.');
} else {
let thirdAnswer = prompt(arthur.thirdQuestion);
if (thirdAnswer != 'To seek the grail') {
alert('Wrong! Into the abyss with ye.');
} else {
alert("You may cross the bridge!")
}
}
}
})
// If user clicks 'Sir Galahad', iterate through questions
galahadButton.addEventListener('click', function () {
let nameQuestion = prompt('What is your name?');
if (nameQuestion != galahad.name) {
alert("Wrong! Into the abyss with ye.");
} else {
let colorQuestion = prompt('What is your favorite color?');
if (colorQuestion != galahad.favoriteColor) {
alert('Wrong! Into the abyss with ye.');
} else {
let thirdAnswer = prompt(galahad.thirdQuestion);
if (thirdAnswer != 'What kind of swallow?') {
alert('Wrong! Into the abyss with ye.');
} else {
alert("I don't know that! Aaargh!")
}
}
}
})

Throw a little CSS in there, and you’re done! You can check out my program below.

As always, I highly recommend playing around with these concepts. Go ahead and make mistakes — even you, fellow perfectionists. After all, the best way to learn to code is to write code — even if it’s not perfect, and if it’s a little buggy. You’ve got this, friends. Happy coding!

Note: this article was originally published in gitconnected’s Level Up Coding publication. You can read it here.

By Ayla Yersel

Humanities nerd learning to code.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s