JavaScript this Keyword

this keyword in JavaScript is used to refer to a specific object. Now the point comes to which object this keyword will refer to. We can have below 4 scenarios for calling this keyword.

  • Global Scope
  • Object’s Method
  • call() or apply() method
  • bind() method

this – Global Scope:
this keyword will point to the window object if the function in which this keyword is used is called from the global scope.

<!DOCTYPE html>
<html>
<body>
<h2>this keyword - Global Scope</h2>
<script>
var mySite = "w3schools.com";
function mySiteTest() {
var mySite = "test.com";
document.writeln("mySite = " + mySite);
document.writeln("this.mySite = " + this.mySite);
}
mySiteTest();
</script>
</body>
</html>

this – Object’s Method

<!DOCTYPE html>
<html>
<body>
<h2>this keyword - object method</h2>
<script>
var mySite = "w3schools.com";
function siteTest() {
this.mySite = "test1.com";
};
var obj1 = new siteTest();
var obj2 = new siteTest();
obj2.mySite = "test2.com";
document.writeln(obj1.mySite);
document.writeln(obj2.mySite);
</script>
</body>
</html>

this – call() or apply() method
call() and apply() methods provide the facility to pass an object as the first parameter to which this keyword refers.

<!DOCTYPE html>
<html>
<body>
<h2>this - call() and apply() </h2>
<script>
var mySite = "w3schools.com";
function thisTest() {
document.writeln(this.mySite);
}
var obj1 = { mySite : "test1.com" , siteTest: thisTest };
var obj2 = { mySite : "test2.com" , siteTest: thisTest };
thisTest();
thisTest.call(obj1);
thisTest.apply(obj2);
</script>
</body>
</html>

this – bind() method
It was (bind() method) introduced since ECMAScript 5. The bind() is used to set the context of this keyword to a particular object when a function is called.

<!DOCTYPE html>
<html>
<body>
<h2>this - bind() </h2>
<script>
var mySite = "w3schools.com";
function TestFunction(callback)
{
var mySite = "test1.com";
callback();
};
var obj = {
mySite: "test2.com",
thisTest : function() {
document.writeln("this: " + this + ", myVar: " + this.mySite);
}
};
TestFunction(obj.thisTest);
TestFunction(obj.thisTest.bind(obj));
</script>
</body>
</html>