본문으로 건너뛰기

Methods

Methods

In JavaScript, an object can have properties and methods. Think of methods simply as "functions of an object."


Examples:

Let's look at several examples of methods for handling strings (length, toUpperCase).

let name = 'banana';

// Method that returns the length of the string
console.log(name.length); // 6

// Method that converts the string to uppercase
console.log(name.toUpperCase()); // BANANA

These methods can be defined not only for primitive data types but also for user-defined objects.


2. Difference Between Methods and Functions:

  • Functions:

    • A function is an independent block of code. It is a collection of code that performs a specific task.
    • A function is not bound to any particular object.
    • Example:
      function greet() {
      console.log('Hello!');
      }
      greet(); // Hello!
  • Methods:

    • A method is a function that is a property of an object.
    • Methods are called within their respective object and often access other properties of the object.
    • Example:
      let person = {
      name: 'John',
      greet: function () {
      console.log('Hello, ' + this.name + '!');
      },
      };
      person.greet(); // Hello, John!