What is This

An overview of JavaScript Classes, this keyword, and explicit function binding

Background

After first learning Ruby in Flatiron’s Software Engineering Bootcamp, JavaScript was at times a bit difficult to understand. When working with Ruby, and it’s popular framework Ruby on Rails, you write code that is encapsulated almost exclusively in classes. You take a blueprint, and instantiate many people with that blueprint. In JavaScript, you have many people, with no blueprint. While ES6 introduced a class structure to JavaScript in 2015, JavaScript is still not intended to be an Object-Oriented language. You can read all about why you shouldn’t be using classes in JavaScript here, but the truth is, classes in JavaScript aren’t going anywhere, and can be helpful in code organization. Here are some things that you should know before using JS classes:

This Keyword

Along with scope, this is arguably the most important concept in JavaScript. Here are the general rules regarding what this refers to:

It may seem pretty straightforward at first, but what happens when you want this to refer to the global object when you’re inside of an event callback function? We can achieve this with the bind keyword

Bind Keyword

MDN’s Javascript Documentation defines bind

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

Put more simply, bind allows us to change the value of this

Additionally, we can use bind to ‘borrow’ methods from other objects in the following manner:

While using bind, it is important to note that the time of function execution is in the future, versus call or apply, where the time of execution is now.

Conclusion

When coming from a background in Object Oriented programming, learning JavaScript can be a daunting task. It’s not as easy to read as other languages, and can be hard to keep track of when code is being executed. With some practice and the logging of this to the console, it wasn’t long before I started to use it naturally in my code, and is an important step in tackling JS. Be patient, and happy coding.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store