MARCUS ÖSTERBERG

JavaScript This

JavaScript This ES6

What is ‘this’ referring to in JavaScript

If you are not aware of how you are using the keyword ‘this’ inside the scope context. this can give you tons of errors and headache.
So let us have a look at some examples of what this is and how we can control it.

Executing this inside our 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.

var world = {
 data: ['denmark', 'germany' ],

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


As we can see 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 have a look on a more practical example.

var world = {
  data: ['denmark', 'germany' ],

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


We can cache this from its surrounding environment and then pass it down the scope chain. Lets create an array in the global Object, declare that and assign it to this.

var data = ['canada', 'sweden'];
var that = this;

var world = {
  data: ['denmark', 'germany' ],

//Swap the keyword this.data to that.data in the display method
  display: function() {
    that.data.forEach(function(element){
      console.log(element.toUpperCase());
    });
  }
};
world.display();
->CANADA
->SWEDEN



Introducing function.prototype.bind() and .call()
We can bind this inside our display method to reference the global Window Object. Like this.

var data = ['canada', 'sweden'];

var world = {
  data: ['denmark', 'germany'],

  display: function() {
    this.data.forEach(function(element){
      console.log(element.toUpperCase());
    });
  }.bind(window)
};
world.display();
->CANADA
->SWEDEN


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

var foo = world.display;


foo dont 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() method.

//Provide world as its enclosing scope
foo.call(world)
->DENMARK
->GERMANY


With Arrow functions in ES6 this is set lexically

var data = ['canada', 'sweden'];

var world = {
  data: ['denmark', 'germany' ],

  display: () => {
    this.data.forEach((element) => {
    console.log(element.toUpperCase());
    });
  }
};
world.display();
->CANADA
->SWEDEN



This has been a brief introduction to this and its scope references. Can be good to know that working in strict mode or sloppy mode can change this behavior.
I hope you found this article helpful and feel free to comment below.

Enjoy your code.


comments powered by Disqus
Archive