Sunday, September 22, 2019

What is this keyword in JavaScript? Explain it with example.

The this keyword is a reference variable that refers to the current object. Here, we will learn about this keyword with help of different examples.

JavaScript this Keyword Example

Let's see a simple example of this keyword.

  1. <script>  
  2. var address=  
  3. {  
  4. company:"Javatpoint",  
  5. city:"Noida",  
  6. state:"UP",  
  7. fullAddress:function()  
  8. {  
  9. return this.company+" "+this.city+" "+this.state;  
  10. }  
  11. };  
  12.   
  13.   
  14. var fetch=address.fullAddress();  
  15. document.writeln(fetch);  
  16.   
  17. </script>  
Output:

Javatpoint Noida UP
The following ways can be used to know which object is referred by this keyword.

Global Context

In global context, variables are declared outside the function. Here, this keyword refers to the window object.

  1. <script>  
  2. var website="Javatpoint";  
  3. function web()  
  4. {  
  5. document.write(this.website);  
  6. }  
  7. web();  
  8. </script>  

The call() and apply() method

The call() and apply() method allows us to write a method that can be used on different objects.

  1. <script>  
  2. var emp_address = {  
  3.     fullAddress: function() {  
  4.         return this.company + " " + this.city+" "+this.state;  
  5.     }  
  6. }  
  7. var address = {  
  8.     company:"Javatpoint",  
  9.     city:"Noida",  
  10.     state:"UP",  
  11.   
  12. }  
  13.   
  14. document.writeln(emp_address.fullAddress.call(address));   
  15. document.writeln(emp_address.fullAddress.apply(address));</script>  

The bind() Method

The bind() method was introduced in ECMAScript 5. It creates a new function whose this keyword refers to the provided value, with a given sequence of arguments.

  1. <script>  
  2. var lang="Java";  
  3.   
  4. function lang_name(call)  
  5. {  
  6.   
  7.     call();  
  8. };  
  9.   
  10. var obj={  
  11.     
  12.   lang:"JavaScript",  
  13.   language:function()  
  14.   {  
  15.     document.writeln(this.lang+ " is a popular programming language.");  
  16.   }  
  17. };  
  18. lang_name(obj.language);  
  19. lang_name(obj.language.bind(obj));  
  20. </script>  

No comments:

Post a Comment