Asked 6 years ago
24 Mar 2018
Views 1218
jaggy

jaggy posted

how to create custom method for object in JavaScript ?

how to create custom method for object in JavaScript ?
sqltreat

sqltreat
answered Apr 25 '23 00:00

In JavaScript, you can create custom methods for objects by defining a function as a property of the object. Here is an example:



// create an object with properties
const car = {
  make: "Honda",
  model: "Civic",
  year: 2020,

  // define a custom method
  startEngine: function() {
    console.log(`Starting the ${this.make} ${this.model}...`);
  }
};

// call the custom method
car.startEngine(); // Output: Starting the Honda Civic...

In this example, we have defined an object car with properties such as make , model , and year . We have also defined a custom method startEngine , which is defined as a function that logs a message to the console.

To call the custom method, we simply call the method using the car.startEngine() syntax. The this keyword inside the custom method refers to the object that the method belongs to, in this case car .

You can define multiple custom methods for an object, using the same syntax as above. Simply define a function as a property of the object and call it using the object's dot notation
Post Answer