Understanding “this” in JavaScript

Understaing "This" keyword in Javascript

Loading

Understaing “This” keyword in Javascript, Function in javascript have properties, Just like javascript Object have properties. And when function get execute, It get the this property

Lets Take a closer look at “this”. this is a special character/keyword in javascript, As we know working with this is little tricky because it can change value when you and you are not expecting

Let see how we can track this in Javascript

First we check this in global context

When we use this in global context that’s mean its not written inside a function scope. It refers to window object in browsers because window object is the top level global object in browser

console.log("This is: ", this);

It will return the window object in browser

Whenever you create a global variable its added to a property of window object. Let see an example these both methods will work same

var myVar = 5;
console.log("My var is: ", this.myVar);
console.log("My var is: ", myVar);
var myVar = 5;
function myFunction(){
  myVar++;
  console.log("My var is: ", this.myVar);
  console.log("My var is: ", this);
}

myFunction();

In that example the value of this will refer to the window object.

Lets see the value of this when we use constructor function

function MyObject() {
  var myVar = 300;
  this.obj1 = 100;
  this.obj2 = 200;
  this.obj3 = function(){
  return this.obj1 + this.obj2;
 }
}
var newObject = new MyObject();
console.log(newObject.myVar); // undefined
console.log(newObject.obj1); // 100
console.log(newObject.obj2); // 200
console.log(newObject.obj3()); // 300

Now in the first case we have created a variable myVar, Which is local to MyObject function. But in other cases this keyword refers to any of the instance we create with “MyObject” constructor function using new keyword. Basically instance is a Object which created by a Constructor Class.

In “MyObject” function this is refers to object which is created from new keyword of constructor class. As i said myVar variable in local to MyObject function. So when we are accessing newObject.myVar it returns undefined because myVar can only be accessable through MyObject function means myVar scope is only for MyObject function scope and it cannot be access by any other object which we create new of MyObject. we have also used concept in two of our project JPG Compressor Online and Youtube Thumbnail Grabber

About Post Author