Defining methods
A method is a function associated with an object, or, put differently, a method is a property of an object that is a function. Methods are defined the way normal functions are defined, except that they have to be assigned as the property of an object. See also method definitions for more details. An example is:
objectName.methodName = functionName;
const myObj = {
myMethod: function (params) {
// do something
},
// this works too!
myOtherMethod(params) {
// do something else
},
};
where objectName is an existing object, methodName is the name you are assigning to the method, and functionName is the name of the function.
You can then call the method in the context of the object as follows:
objectName.methodName(params);
Methods are typically defined on the prototype object of the constructor, so that all objects of the same type share the same method. For example, you can define a function that formats and displays the properties of the previously-defined Car objects.
Car.prototype.displayCar = function () {
const result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
console.log(result);
};
Notice the use of this to refer to the object to which the method belongs. Then you can call the displayCar method for each of the objects as follows:
car1.displayCar();
car2.displayCar();Using this for object references
JavaScript has a special keyword, this, that you can use within a method to refer to the current object. For example, suppose you have 2 objects, manager and intern. Each object has its own name, age and job. In the function sayHi(), notice the use of this.name. When added to the 2 objects, the same function will print the message with the name of the respective object it's attached to.
const manager = {
name: "Karina",
age: 27,
job: "Software Engineer",
};
const intern = {
name: "Tyrone",
age: 21,
job: "Software Engineer Intern",
};
function sayHi() {
console.log(`Hello, my name is ${this.name}`);
}
// Add sayHi function to both objects
manager.sayHi = sayHi;
intern.sayHi = sayHi;
manager.sayHi(); // Hello, my name is Karina
intern.sayHi(); // Hello, my name is Tyrone
this is a "hidden parameter" of a function call that's passed in by specifying the object before the function that was called. For example, in manager.sayHi(), this is the manager object, because manager comes before the function sayHi(). If you access the same function from another object, this will change as well. If you use other methods to call the function, like Function.prototype.call() or Reflect.apply(), you can explicitly pass the value of this as an argument.