We build your ideas. Contact us for Mobile/Web App Development. Write us @ contact@milanjeet.com

var self = this; confusion in Javascript

var self = this;

While learning Javascript, we see something a lot var self = this; which is a confusion point for most of the learners. They keep this topic in aside to learn it later and then don’t really read it as this seemed the confusion topic in Javascript. Even me while learning Javascript, I used to see this a lot. Why don’t we use this instead. Later I found the life of self after going through Google forms.

Self is just a variable nothing else. Self saves the object’s context to access the values to inner function. It comes under Javascript Closures.

Let’s understand the above with below example.

var obj = {
    outerFunction: function() {
        console.log(this == obj) // will return true;
    }
}

obj.outerFunction();

 

this is not a variable instead it is a Javascript Keyword used to store current context of the object. obj.outerFunction() is a method invocation on ‘obj’ Object. So the context in outerFunction() refers to ‘obj’ and therefore this == obj evaluates to true. That means this is referring to the current / expected object. Now let’s see below example.

var obj = {
      outerfunction: function() {
          console.log(this == obj) // true
          function innerfunction() {
              console.log(this == obj);  // false
          }
          return innerfunction;
      }
}

var j_pro_inner = obj.outerfunction();
j_pro_inner();

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)