Javascript this keyword

This keyword represents the instance of the current object in the method of the class and it is only relevant within a method of the class, i.e we cannot use it outside of a method. We can use this keyword in the global and function contexts. Moreover, the behavior of this keyword changes between strict and non-strict mode

Input:-
 <script>  
	   var project = {  
        language:"HTML",  
        version:"5",   
        projectDetail:function(){  
            return this.language+" "+this.version;  
        }  
    };  
    var fetch = project.projectDetail();  
    document.write(fetch);
</script>

Output:-


Global context

In the global context, this references the global object, which is the window object on the web browser or global object on Node.js.

This behavior is consistent whether the strict mode is applied or not.

If we assign a property to this object in the global context, JavaScript will add the property to the global object as shown in the below example:-

Input:-
 <script>  
	   var language="HTML";  
    function lang() {  
        document.write(this.language);  
    }  
    lang();
</script>

Output:-


Call() and apply() method

These method allows us to write a method that can be used on different objects.

The apply() method is similar to the call() method except that its second argument is an array of arguments.

Input:-
 <script>  
	   var project_detail = {  
    	fullDetail: function() {  
         	return this.language + " " + this.version+" "+this.developer;  
   	}  
    }  
    var project = {  
        language:"HTML",  
        version:"5",  
        developer:"Mike"
    }  
    document.write(project_detail.fullDetail.call(project));   
     document.write(project_detail.fullDetail.apply(project));  </script>

Output:-


Bind() method

This method creates a new function whose this keyword refers to the provided value, with a given sequence of arguments  and was introduced in ECMAScript 5.

Input:-
 <script>  
	   var lang="React JS";  
    function lang_name(call){  
         call();  
    };  
    var obj={  
        lang:"Javascript",  
        language:function() {  
             document.write(this.lang+ " is a popular programming language.");  
        }  
    };  
    lang_name(obj.language);  
    lang_name(obj.language.bind(obj));
</script>

Output:-