This and That, mostly this.

The question of “What is this?” can be a tricky one. Even outside of programming context is required. Can I see it? Do I know who is asking me? Is it blue? Let’s focus in on what it means in computer science, even more specifically what does it mean in Javascript?

Mostly this has a value that is determined by how a function is called. We also know it can’t be set by assignment during execution. It can also be a different value each time the function is called. What have we learned so far? It is all about context. There are options such as bind
to set the value inside a function regardless of how it was called. There are also some ECMAScript 2015 ideas called arrow functions where this
is lexically scoped (it is set to the this value of the execution context closure).

Still not super clear. Time to dig a little deeper.

Starting with the global context.

Open the developer console and type this. You get a huge object. With so many properties that it is not easy to visually parse. Looking at a few of the more familiar ones what do we see?

this.Array === Array; // true

this === window; // true

this.a = 37;
this.a === window.a; // true

As we see the value of this in the above context is the global object (window in the case of a browser). How does this change in a function?

function thisFunction1() {
  return this;
}

thisFunction1() === window; //true

function thisFunction2(){
 "use strict";
  return this;
}

thisFunction2() === undefined; //true

Since in thisFunction1() this is not defined by the call AND because its not in strict mode the value of this defaults back to the window option. We see in the second example thisFunction2() the value of this remains at the value set when entering the execution context. If it is not defined we get… undefined!  It’s getting a bit more clear, I can still read through it though.

Arrow Functions? I have recently become a huge fan of arrow functions. They are clear to read, shorten my code and now I can more easily understand what this would be during function execution.

It looks like when you initially define the this value it will stick. It will also be set for any calls to functions that live as object methods if the object method is an arrow function. There is a great example on developer.mozilla.org Even functions within functions the this value stays tied to the outer execution context.

More on object methods, not just fat arrow style.

var objectWithMethods = {
  someValue: 42,
  usefulMethodName: function() {
    return this.someValue;
  }
};

console.log(objectWithMethods.usefulMethodName()); // logs 42

 

When making a function that will be used as a constructor with the new keyword its this will be bound to the new object.

More on this later!