JavaScript this Keyword

this keyword in JavaScript is used to refer a specific object. Now the point comes to which object this keyword will refer. 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 points to the window object if the function in which this keyword is used called from the global scope.

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

Output

this keyword - Global Scope
mySite = test.com this.mySite = w3spoint.com

this – Object’s Method

<!DOCTYPE html>
<html>
<body>
	<h2>this keyword - object method</h2>
	<script>
 
	var mySite = "w3spoint.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>

Output

this keyword - object method
test1.com test2.com

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

<!DOCTYPE html>
<html>
<body>
	<h2>this - call() and apply() </h2>
 
	<script>    
	var mySite = "w3spoint.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>

Output

this - call() and apply()
w3spoint.com test1.com test2.com

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

<!DOCTYPE html>
<html>
<body>
	<h2>this - bind() </h2>
 
	<script>    
		var mySite = "w3spoint.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>

Output:

this - bind()
this: [object Window], myVar: w3spoint.com this: [object Object], myVar: test2.com
Please Share