Marcus Osterberg
2 min readMay 5, 2016

What context is this

Get rid of all the scooping errors, lets learn about how we refer to the context object in JavaScript with the keyword this.

Executing this inside our browsers console would return the global object window:

this // window { external: Object, .... }

Lets create a object called world with a method called display that returns this:

const world = {
data: ['Denmark', 'Germany' ],

display() {
return this
}
}
world.display() // Object { data: Array[2] }

The returned context of this is no longer referring to the global window object, it’s now referring to the enclosing execution context which is the world object.

So now that we know when this is this lets access this data:

const world = {
data: ['Denmark', 'Germany' ],

display() {
this.data.forEach(element => console.log(element.toUpperCase()))
}
}
world.display()
->DENMARK
->GERMANY

Very often you find your self want to access data from another scope inside of your context.
It’s useful to know how to access a scope from a contexts surrounding environment. Introducing function.prototype.bind() and .call().
We can bind the context of display to reference the global window object:

const data = ['Canada', 'Sweden']const world = {
data: ['Denmark', 'Germany'],
display: function() {
this.data.forEach(element => console.log(element.toUpperCase()))
}.bind(window)
}
world.display()
->CANADA
->SWEDEN

Lets declare a variable and assign it to the display method:

const foo = world.display

foo don’t know display methods original surrounding context and refer this to the global window object instead of world.

foo()
->CANADA
->SWEDEN

We can provide the original scope for this, by using the .call():

// Provide the world object as the context of this
foo.call(world)
->DENMARK
->GERMANY

This has been a brief introduction on how to reference scopes context in JavaScript using the keyword this. Please let me know in the comments below if you found this helpful or have anything to add.

Keep on learning JavaScript and enjoy your code.

Marcus Osterberg

Swedish. I like to code, learn new things and travel new places.