Skip to content

Context

ParvinBDJ edited this page Jun 20, 2020 · 4 revisions

Context

So context... THIS is, in my eyes, a very hard concept to explain. But I will try my very best to explain it as well as I can. Context is kind of like scope, only scope is function-based and context is object-based.

So context refers to the object where a function belongs to. When you use the keyword this you can find out in what context the function is currently in. There are 2 different contexts where an object can be inside.

  1. Inside the Object
  2. Global (Mac = window, Windows = global)

Inside the Object means that the function is inside of the object. You can check that by usingthis. Now we will see if it works. I put a function inside of an object and in there tried to console log this. Now we should see the object inside of the console.log

const objA = {
  firstName: "Parvin",
  function sayName(){
    console.log(this);
  }
};

objA.sayName();
// -> {name: "Parvin", sayName: f}

So in here this is connected to the objA which is why this console logs the whole object. But you might be thinking "mmmm I still don't understand". Well, look, if you were to add another function inside of the object but write it outside of it. Like this:

const objA = {
  firstName: "Parvin",
  function sayName(){
    console.log(this);
  }
};

objA.sayThis = function(){
  console.log(this);
};

objA.sayThis();
// -> {name: "Parvin", sayName: f, sayThis: f}

This is the same because it is referring to the same object!! This is very important to understand.

Global (window) means that this is inside the global object. Let me demonstrate:

function sayName(){
  console.log(this)
  }
}
sayName();
// window {postMessage: f, blur: f, focus: f,  close: f, frames: Window, ...}

Now, this is referring to the global object (window). See?

Sources

Clone this wiki locally