Context and Function Binding

Context is King (this)

Context in Javascript is just this. It’s important to understand the context in which you are executing your code. It’s quite similar in concept to scope, with a few important differences:

  • Context is object-based and can be changed at run time.
  • Scope pertains to the variable access of a function or a program when it is invoked and is unique to each invocation.

For example, you can tell the scope by just looking at the code. You cannot tell the context without running the code.

Simple put, context is always the value of the this keyword which is a reference to the object that owns the currently executing code.

For example, in your browser, if you simple console.log(this), you get the current context. Which in the case of the browser, is the Window object.

Try it!

Try opening your Chrome dev tools and console.log(this). You’ll get back an Object (the Global Object).

(this) returns the Window object

Take a look at the Codepen below:

In this example, we’re displaying the constructor’s name property, which is the Class name of the object. In this case it’s Window because we’re running this code in the browser’s Window context.

In this next example, we’re doing the same thing, except within a function. Notice how we are executing this code within the same context. If we were talking about scope, then the scope would be within the function.

Now, let’s try and get a different context instead of the Window object.

Why would you need this?!

Because maybe you want to re-use the same function on different objects (meaning, different contexts)!

There are a at least two ways we can change our context:

Method 1: You can move the function inside an object or a Class:

The value of this inside the helloMyNameIs()method in this case is the student object. All we had to do was call the function attached to the student object.

Method 2: Using function binding

This example is generally considered to the correct way of changing your context. This is because you can declare you function, and you don’t need to keep it locked inside of an object in order to access it’s this.properties.

Now that we have an understand of function binding, we can move on to talk about event handling and state in React.