The current project includes JavaScript Constructors in external files for use from the node command line. We’ve been warned that as we dive into our own constructors, especially while using the this keyword, use the rule of Inception – never go more than three levels deep.

This is going to be a post about frustration. Of course, you might have already figured that out when I used the word this.

This Is Frustrating

My project, a new Hangman game, goes farther than the actual requirements. I’m actually pulling random movie titles from the OMDB API and using them as my puzzles to solve. One thing I need to ensure is that the movie title is actually obtained before my asynchronous code moves forward, or I’ll get all kinds of undefined errors.

Node Hangman: "This" Error

Bind() to the rescue! It’s getting difficult to create an arrow function to a function located within the same Constructor, but bind() did the job perfectly.

This Is Impossible

I’ve also created a Constructor for the Game Control, which I’ve brilliantly called GameControl. It will store all of the game logic and game functions that don’t specifically create the puzzle word or its letters. The project, after all, asks me to use as many Constructors as possible! So I’ve created a GameControl Constructor, and I’ve simply called it controls. It will be used in the various functions inside the Word Constructor.

var GameControl = require("./gameControl.js");
var controls = new GameControl();

But now that I’m in the GameControl Constructor, how do I actually affect any of the variables stored inside of my new objects? The globals can’t actually be called from inside an external Constructor, and this doesn’t translate well across multiple files and inside multiple encapsulations.

I finally realized that I simply need to pass this into the controls object.

controls.userOptions(this);

Great! I can now control a Word object from inside the GameControl prototype! But now, I can’t actually control the GameControl variables from within the GameControl Constructor, because I’ve gone too deep into encapsulation again, and this still doesn’t function correctly for the controls.

Node Hangman: "This" Error

Am I just doomed? I mean, there must be a way to do what I want, right?

This Is Brilliant

The solution, when it finally hit me, was actually pretty simple. Let’s pass the controls object, which was created from the GameControl constructor, back into itself so it can update its own parameters no matter how deep the rabbit hole goes!

controls.userOptions(this, controls);

Node Hangman: "This" Success

This actually works! At this point, I’m actually passing an object back into its original Constructor Prototype as a variable, continuing to pass it into a function inside of a function inside of a function (all within the original Prototype), and finally referencing it 4 encapsulations deep with perfect success.

Node Hangman: Working Output

For some reason, my top is still spinning…