JAVASCRIPT Tutorial

Object Methods

What are Object Methods?

In programming, methods are functions associated with objects. They define the behavior an object can exhibit.

Key Concepts:

  • Methods: Actions or operations that an object can perform.
  • Functions: Reusable blocks of code that perform specific tasks.
  • this Keyword: References the current object within a method.

Practical Steps to Define Object Methods:

  1. Create an Object: Define a blueprint for objects using a class or constructor function.
  2. Add Methods: Add function definitions to the object's prototype property.
  3. Use Methods: Call methods using the dot operator ..

Example in JavaScript:

// Create an Employee object
const employee = {
  name: "John Smith",
  salary: 10000,
  // Define the getSalary() method
  getSalary: function() {
    // Use 'this' to access the object's properties
    return this.salary;
  }
};

// Call the getSalary() method
const salary = employee.getSalary();

console.log(`Employee ${employee.name} earns $${salary}.`); // Output: Employee John Smith earns $10000.

Conclusion:

Object methods provide a structured way to define and execute actions on objects, enhancing their reusability and code organization. By understanding these concepts, developers can easily create and manipulate objects with specific behaviors.