Using this keyword in JavaScript.

this keyword in JavaScript is a The value that this stores is the current execution context of the JavaScript program. Thus, when used inside a function this‘s value will change depending on how that function is defined, how it is invoked and the default execution context.

this always holds the reference to a single object, that defines the current line of code’s execution context.

<script>
var myVar = 100;

function WhoIsThis() {
    var myVar = 200;

    alert(myVar); // 200 variable which created Inside the function. 
    alert(this.myVar); // 100 variable which created outside the function.
}

WhoIsThis(); // inferred as window.WhoIsThis()

var obj = new WhoIsThis();
alert(obj.myVar); 
</script>

In this example we can understand about this keyword.

The following four rules applies to this in order to know which object is referred by this keyword.

  1. Global Scope
  2. Object’s Method
  3. call() or apply() method
  4. bind() method.

Leave a comment

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