
Join the Conversation!
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.
In this lesson, you'll learn about methods in JavaScript, which are functions associated with objects. Methods are a fundamental concept in object-oriented programming and are used to define behaviors for objects.
A method is a function associated with an object. Simply put, a method is a property of an object that is a function. Methods allow objects to perform actions and are defined similarly to regular functions, but they are assigned as properties of an object.
Methods can be defined in two main ways:
var myObj = {
myMethod: function(params) {
// ...do something
},
// OR using shorthand syntax
myOtherMethod(params) {
// ...do something else
}
};
In this example, and are methods of .
You can assign a function to an object property, making it a method:
objectName.methodname = functionName;
Where is an existing object, is the name you are assigning to the method, and is the name of the function.
You can call a method in the context of the object as follows:
object.methodname(params);
You can define methods for an object type by including a method definition in the object constructor function.
For example, let's define a function that formats and displays the properties of objects:
function displayCar() {
var result = `A Beautiful ${this.year} ${this.make} ${this.model}`;
pretty_print(result);
}
Here, is a function to display a formatted string. Notice the use of to refer to the object to which the method belongs.
You can make this function a method of by adding the statement:
this.displayCar = displayCar;
So, the full definition of would now look like this:
function Car(make, model, year, owner) {
this.make = make;
this.model = model;
this.year = year;
this.owner = owner;
this.displayCar = displayCar;
}
You can call the method for each of the objects as follows:
var car1 = new Car('Toyota', 'Corolla', 2020, 'Alice');
var car2 = new Car('Honda', 'Civic', 2019, 'Bob');
car1.displayCar();
car2.displayCar();
Methods are a powerful feature in JavaScript, enabling objects to have behaviors and perform actions. Understanding how to define and use methods is essential for working with objects and building complex applications.
"Please login to view comments"
Subscribing gives you access to the comments so you can share your ideas, ask questions, and connect with others.