Avelyne Flatiron Blog

This is This

June 26, 2019

The Elusive Concept of “This”

gif

So we’ve heard a whole bunch of times when we’ve been looking at JS not to worry about this and how JS handles this. But we’ve done some Rails now so we have some idea of what self is, so this is basically that, right?

Nah,

gif

So in javascript, a function can be called with any context. Usually, you will call a function on an object like this: object.function(); and inside the function “this” will be the result you expect. Strictly speaking it is an object that exists as a property of any execution.

example

Often you bind this to another variable, like let self = this

in this case, self is being used to maintain a reference to the original this even as the context is changing. It’s a technique often used in event handlers (especially in closures).

example

The value of this is determined by how exactly the function is called. It can’t be assigned during the actual execution of a function and like Ruby’s self it can be different every time a function is called.

In arrow functions, this retains the value of the contextual this.

example

But this often leads to some confusion, especially now that modern browsers have a globally assigned value of “self” which refers to the window. https://developer.mozilla.org/en-US/docs/Web/API/Window/self

gif

So you can’t use self and you can’t really use this as it’s not even a 100% given as to the data type that is sent back well how else are you going to refer to a functions this?

gif

You could say we’re in a bit of a bind.

So this is where bind comes in.

Bind

Using Function.prototype.bind() you can specify the value that should be used as this for any calls to a function. This clears up some of the confusion to do with exactly which this you’re referring to.

example


Sam Barrie

Written by Sam Barrie who lives and works in London and studies at Birkbeck University and Flatiron School. Feel free to check him out on Linkedin or GitHub.