Before discussing the difference between a function and a method, we must understand, what is a function and what is a method. So, let’s understand a function first.
function greet() {
console.log("Hello, world!");
}
greet(); // Calls the function
So, we can say that
Now, Let’s see, what is a method
Definition – When a function is defined as a property of an object or a class, it is called a method of that object or the class.
const person = {
name: "Rajesh",
greet: function() {
console.log("Hello, my name is " + this.name + "!");
}
};
person.greet(); // Calls the method
class person {
name;
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
let obj = new person();
obj.name = "Rajesh";
obj.greet();
function | method (object) | method (class) |
We need to use function keyword while defining a function | We need to use function keyword while defining a method associated to an object | function keyword should not be used when we define a method associated to a class |
We can call function without using any object reference | We have to use object reference for calling method | We have to use object reference for calling method |
Functions are general-purpose blocks of code that can be used independently | methods are specific functions associated with an object | methods are specific functions associated with a class |
In a standalone function, this can have different values depending on how the function is invoked. | In a method, this refers to the object to which the method belongs, allowing methods to access and modify the object’s properties | In a method, this refers to the object to which the method belongs, allowing methods to access and modify the object’s properties |
Mostbet Turkey: Profesyonel Musteri Destegi
Heyecan Verici Kazanclar icin Gates-of-Olympus Slot
In JavaScript, an object is a data structure that allows you to store collections of…
Objects, Classes and Constructor in Javascript Classes and Objects A class in any programming language…
We will start from object oriented programming basics like What are different concepts in Object…