Category Archives: Programming

Posts here deal with existing engines and programming and stuff.

JavaScript: Abusing “this”

This post is an adaptation and expansion of a recent lightning talk I gave.  You can find the original slides here.


Let’s talk about the way  this works in JavaScript.

The first thing you learn when you’re studying JavaScript is that you can never assume it works the same way as another language.  For example, in a normal language,  this is a variable that is defined at compile-time.  It’s used within code to refer to a property on the current object you’re writing for. In JavaScript,  this means something else entirely.  It’s easy to miss the differences at first, because when used in a very straightforward manner,   this seems to exhibit some of the same behaviors.  It’s only when you start to experiment that everything breaks down.

If you’re like me, you probably once took an introductory web development class and had all of the confusing stuff with  this explained to you in the following manner, using the following code:

This is a fairly inaccurate way of describing what’s actually going on, and it shouldn’t take us long to poke some holes in it.

The first thing that should spring to mind is that myPublicProperty breaks as soon as we access it without the this keyword. Which is slightly weird. Also, we run into scenarios like below:

So we could play around with these edge cases all day, but there’s not much of a point.  If you’re really interested in getting a complete picture of what this actually is, I have a number of articles I’ll recommend at the bottom of the post. Otherwise, I’m just going to give you a quick interpretation that is, at least for our purposes, fairly accurate.

Assume that this is a global variable. When we call a method, this gets set to that method’s current scope. Per example, the below code :

Whenever you use this internally, you’re making a call to the object being stored in this global variable, and all of your data and method calls and so on happen relative to the object in that variable.  Simple enough, right?

Call and Apply

The important thing to remember is that JavaScript sets this at runtime, while the code is still executing. If we could change the definition of this before we called a method, we could do some cool stuff. And it turns out we can.

In fact, this is pretty much how JavaScript makes new objects in the first place.

What methods like  call allow us to do is to invoke a method and pass in an object that we want to use as the new   this for the duration of that method call.  And what that allows us to do is Object Oriented Programming on a very fundamental level.

Context is everything

For example:

JavaScript checks to see that a method exists before it allows you to call it, but it almost never checks to see that the method is being called in a context that makes any sense at all.  It’s not an oversight, it’s a feature.  But it’s a feature with a wild potential for abuse.

Another interesting feature of JavaScript is that it sometimes uses this internally.

We just got JavaScript to push an element onto the number 5, then pop it back off.  And the absolutely amazing, fantastic thing about all of this is that it worked perfectly.  No errors at all.

And yes, it’s a little bit tricky that we made a new number instead of sticking with a primitive, but the point still stands.

 A mild case of legitimacy

So, inheritance.  Here’s a fairly good method of doing it, as stolen from John Resig.

Wait, wait, don’t leave yet!  We can simplify all of this!

Good, you’re back.  So it’s not going to be as production ready, and we won’t get any of the nice typeof behaviors or even proper method overriding, but what if I told you we could get inheritance working in one line of code, without worrying about prototype or anything complicated like that?

In fact, let’s go a step farther and make multiple inheritance:

Easy, right?

All we have to do is take advantage of some of the things we already know about  this  and how objects get created in the first place.  We use our parent classes as constructors, but instead of making new objects, we just run those constructors with our new object as the current context., "meow");

The result is that we’ve basically just chained two constructors together.  And again, half of object creation takes place in the constructor anyway, so we’re not really breaking any of the existing JavaScript tenants.

Again, there are some weaknesses with this method, many of which you can probably come up with on your own.

And there are many good questions you could ask right now that I’m not going to answer:

  • “What happens if I inherit from two parents that have methods or properties that share the same names?”
  • “What if I do want to have method overriding and be able to call base and super without breaking stuff?  How would I do that?”
  • “Isn’t it inefficient to be recreating all these methods every time I make an object?”

But still, if you were working on a tight schedule for a class or side-project, and didn’t really understand how the Prototype works, this would be a perfectly reasonable, if somewhat limited solution you could use in your actual code.

Yay, JavaScript!

Some follow-up links

To be expanded as necessary.

What I’m up to: Viral Functions

I’ve been working on a little side project for the past week that gets functions in Javascript to infect other functions and wrap them in custom snippets of code.   It’s modeled after how viruses in the body attack cells and reprogram them to build more viruses.

It’s largely an exercise in curiosity at the moment, I don’t really know how effective it will be or what I could end up doing with it.  I had a working version that I ended up forgetting to save on jsFiddle, which was a huge bummer because I don’t remember how the heck I made it work.

Recently I recreated the base using (I think) a different method.  Contrary to many other objects, functions in Javascript are passed around by value, not reference, because Javascript.  Normally you’d wrap the function in an Object, but since I won’t be able to do that with the final product, I use a different method to make sure I’m accessing the actual function and not just a copy.

I believe the below fix would only be necessary on functions in the global context, but I haven’t done any testing to confirm this.  I wish I could find my original code.


I’ll keep the blog updated if anything interesting happens with it.

Culture Shock

Mid 2013, I participated in a Microsoft sponsored development jam with two of my roommates, Robert Adams (The Organizer) and Sean Brennan (Eyes Open).  Sean wanted to do something with AI, particularly with how an agent might see something happen and misinterpret what was going on, so for 48 hours we played around with that concept and the result was Culture Shock, a simulation of cultural conflict and individual biases and preconceptions. Continue reading

Javascript : Functions are Objects

Let’s talk about the different ways variables can work in Javascript. This stuff confused the heck out of me when I first started learning it, so I’m going to go over a lot of the different edge cases and try and give a more complete overview of what’s happening when you declare a variable.

What you should know going into Javascript is that it works differently than a typical object oriented language.

Continue reading

How do we save replays?

Why save replays?

I’ve personally spent a ton of time watching people play The Binding of Isaac (and a good many other games) on youTube, so I have a lot of fondness for the Let’s Play community.  Eyes Open is a short game meant to be replayed multiple times in a row, and in my opinion it’s going to lend itself well to this genre of video.

There’s a problem though : you spend a lot of time with your eyes closed, which means for a lot of the game it’s tough to see what’s going on – and frustrating to watch.  Spectator Mode was and is designed to alleviate this problem.  We’re still in very experimental stages with the system; to be honest I’ve coded enough to be sure that it will work in the final game, and left it at that.  There’s a lot more to do with the game, so I didn’t want to focus on it too early. Continue reading

Halloween Point and Click Postmortem

Halloween was a mid quarter project for college I designed and put together over the course of about two weeks.  It represents some of my first attempts to design lighter game experiences, and to tailor those designs to young audiences.  It also represents the first real flash development I’ve done since eleventh to early twelfth grade, so that’s all very exciting.

As usual, all of the code and documentation you’ll get here has been unaltered in any way from the original submitted version; so all of the successes and failures are on display if you’re into that kind of thing.

I like to try and connect my school assignments to the real world whenever possible.  The specifications for my project required a point and click style “greeting card”, make of that term what you wish.  I more directly took inspiration from my niece’s iPad and some of the gorgeous point-and-click apps that she loves.

One of the things that bothers me with our approach to toddler development in the game industry is that we rarely focus on multi-step exploration or problem solving.  We have a lot of really amazing, well designed experiences that allow young kids to play with the world and have it respond to them, but they usually focus on breadth of choice rather than depth of choice.

I decided to go for the opposite approach; rather than have a lot of things that you could click on, I would focus on affecting the state of the world.

You can see a screenshot of some of the (limited) results below:

Light on
 Light off

With only around two weeks to formulate the design and code, there weren’t a huge number of behaviors I could implement.  In the download, you can see my submitted design doc which runs over the entire list of features.  In the interest of some brevity, I won’t run over most of them, but I will touch on one decision in particular before I go into the code analysis and lessons I learned.

Halloween is designed to be used with a touch interface; project requirements necessitated that I provide rollover effects for the pumpkin, and they’re also the reason for the somewhat awkward credits and intro screen.  All of these (and a few other things) will be removed or redesigned before my niece gets her hands on the finished version.

One of the things I noticed about my niece’s interaction with iPads in the past was that she liked to click around the screen almost at random.  I wanted to give her an avenue to do that in a predictable way, no matter what state the screen was in.

The leaves filled this function: they fall continuously, and the user can click on them at any point to crumple them up, drag them around the screen, and then release them to watch them fall through to the bottom of the screen.  No matter what is happening on the screen, this is always possible.  It’s an extremely shallow mechanic that actually adds a lot of feel to the scene, hunting and pecking feels almost like a game in and of itself.

This fit into my philosophy of exploration over puzzle solving.  I didn’t want this to be a frustrating experience, so I designed the elements (all of them that I had time to get to) such that they would always react to touch in some way, regardless of what’s going on around the screen.  There’s more I could say about this, but if you’re interested I go into more detail in the final design doc that’s up for download below.

I wrote a lot of hacky in-the-moment code this quarter, just like I’ve done a lot of hacky in-the-moment design, a result of me overloading on classes and having to budget my time more effectively than normal.  This project is a good example.

There are two lines of thought that run through my head when I get into situations like this: One is that coding is a means to an end, and if the final game is bug-free (it is) and plays well, bad code is, while not ideal, also not a tragedy.  Secondly, as a person who gets very worked up about making intuitive class structures, I don’t really believe any of that, at least not on an emotional level.  Bad code is often necessary; it’s sometimes quicker.  But I’m not sure it’s ever a good thing.  It’s a matter of priority, sometimes it’s just a loss you have to take.  Case in point, going back and redesigning this project from the ground up would be a nightmare.  There are a lot of things that came out really well, the code structure… eh. Not so much.

Cutting my losses isn’t something I’m usually happy to do.  I like to know that I’ve done my best on a project in all areas.  Learning that this isn’t always possible is a valuable lesson, but it’s a bitter pill to swallow, especially when it comes in an area like the design of a program, which I feel I do fairly well. If anything, I wanted to sacrifice the details of how the actual code worked.  My class hierarchy wasn’t supposed to be a problem.

 In many ways, this entire quarter has been a lesson to me in scoping and polish.  I tend to think of scope as a matter of ambition and project size, but what I’ve been learning is that for many of my projects, even if they’re small, is that I’ll always wish I could have invested more time and thought into decisions.  For many of these projects (like this) I now have the opportunity to go back after class and fix the designs before I release final versions.  That isn’t always usually case though, especially as I move on to other projects.  It’s frustrating, but it’s something I need to learn to deal with.

On a more encouraging note, I got a chance mid-way through the quarter to demo this project at a local museum.  I got a lot of kids to come around my laptop and mess with my touchpad trying to crumple up leaves, and that was really really special for me.

It was extremely interesting for me to see the way they approached the whole experience.  There wasn’t a large amount of time for them to explore, so I walked each child through the different interactions.  What engaged them in most cases was something that I’ve taken to somewhat ignorantly calling Emergent Narrative.  Namely, they liked that I gave them motivations and personalities to project into the situation.  There’s a man that refills the candy dish when you knock on the door.  I told users that he was afraid of the dark, and that turning off the light would cause the man to slam the door in fear and not come out, and the kids were really amused by this.  I was kind of surprised how easily they saw an arm as a person, and how willing they were to attach narrative and personality to that individual.  This is worth exploring more.

Downloads and copyright information below -

You may feel free to reuse this code for any purpose, commercial and proprietary included.  The nice thing to do would be to credit me, but I’m not going to get mad at you if you don’t.

You are not free to reuse or adapt mechanics, artwork or design documentation without written permission from me.  In the event that I’ve forgotten a contributor to this project, all rights of that contributor remain.  Font used is Ubuntu; all rights remain with Carnonical under their original license.