How to use‘this’ keyword in Javascript
In JavaScript, the ‘this’ keyword refers to the current object . This approach is particularly useful when we define a methods within object constructors or object literals.
Example: This example shows the use of “this” keyword for accessing the object properties.
Javascript
// Define an object constructor function Person(name, age) { this .name = name; this .age = age; // Method that uses 'this' to // access object properties this .greet = function () { console.log( "Hello, " + this .name + "! You are " + this .age + " years old." ); }; } // Create an instance of the Person object let person = new Person( "Geeks" , 25); // Call the method using 'this' person.greet(); |
Output
Hello, Geeks! You are 25 years old.
How to Pass Object as Parameter in JavaScript ?
We’ll see how to Pass an object as a Parameter in JavaScript. We can pass objects as parameters to functions just like we do with any other data type. passing objects as parameters to functions allows us to manipulate their properties within the function.
These are the following approaches:
Table of Content
- Passing the Entire Object In a function
- Destructuring the Object
- Using ‘this’ keyword
Contact Us