this Keyword in Javascript
In this chapter, you will learn about, what this Keyword in Javascript. The creation of this keyword is the last property of an execution context. If you don’t remember the execution context object in javascript, please read the chapter about Execution context and come back.
this Keyword is stored in the execution context object and this variable only assigned a value when the object calls the method.
Regular function: In regular function, this keyword points to the global object, the global object is nothing but a window object
Method call: The this keyword points to the object that is calling Method.
this keyword is not assigned a value until a function where it is defined is called.
Let’s see the below example,
function getName(name){ console.log(this); } getName('Stark'); // output // Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
this instance in the above example is printing the window object, as it is pointing to the global object. Now see another example
// lets create an object const person = { name: 'Stark', dep: 'IT', salary: 5000, phoneNumber: 9988000, fullName: function(){ console.log(this); } }; console.log(person); // output // {name: "Stark", dep: "IT", salary: 5000, phoneNumber: 9988000, fullName: ƒ}
In the above example, we are using this keyword inside the fullName function, and this is pointing to the person object. Now add one more function inside it.
// lets create an object const person = { name: 'Stark', dep: 'IT', salary: 5000, phoneNumber: 9988000, fullName: function(){ console.log(this.name); console.log(this); function getAddress(){ console.log(this); } getAddress(); } }; person.fullName() // output // Stark // {name: "Stark", dep: "IT", salary: 5000, phoneNumber: 9988000, fullName: ƒ} // Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
As we can see in the above example, this instance inside the getAddress is pointing again to the global object.
Let us understand the point “this variable only assigned a value when the object calls the method” and write the example for the same
// lets create an object const person = { name: 'Stark', lastName: 'John', dep: 'IT', salary: 5000, phoneNumber: 9988000, fullName: function(){ console.log(this.name+' '+this.lastName); } }; // lets create an object const person2 = { name: 'Salman', lastName: 'Khan', dep: 'IT', salary: 5000, phoneNumber: 9988000 }; person.fullName() person2.fullName = person.fullName; person2.fullName(); // output // Stark John // Salman Khan
2 thoughts on “this Keyword in Javascript”
Comments are closed.