JavaScript this keyword - LearnHowToCode SarkariResult.com Interview Questions and Answers LearnHowToCodeOnline
JavaScript this keyword

JavaScript this keyword

JavaScript this keyword 

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:"learhowtocode",  
  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:
learnhowtocode 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="learnhowtocode";  
  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:"learnhowtocode",  
  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>  

About Mariano

I'm Ethan Mariano a software engineer by profession and reader/writter by passion.I have good understanding and knowledge of AngularJS, Database, javascript, web development, digital marketing and exploring other technologies related to Software development.

0 comments:

Featured post

Political Full Forms List

Acronym Full Form MLA Member of Legislative Assembly RSS Really Simple Syndication, Rashtriya Swayamsevak Sangh UNESCO United Nations E...

Powered by Blogger.