Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript Object Methods

Object methods are functions attached to objects, used to operate on their data.

They often rely on this to access other properties.

Why We Need It

Methods keep logic close to the data it uses, which makes code more readable.

Understanding this inside methods prevents bugs.

Syntax

const obj = { method() { ... } }
obj.method()

Basic Example

1. Basic method

const user = {
  name: "Ava",
  greet: function() {
    return "Hi " + this.name;
  }
};

console.log(user.greet());

Methods can access properties via this.

Real World Example

2. Shorthand

const user = {
  name: "Ava",
  greet() {
    return "Hi " + this.name;
  }
};

console.log(user.greet());

Method shorthand is concise.

Multiple Use Cases

Functions as Properties

Methods are functions stored on objects.

They can access other properties using this.

Method Shorthand

You can define methods using shorthand syntax.

It makes objects cleaner and easier to read.

this Binding

this refers to the object the method is called on.

Be careful when passing methods as callbacks.

More Examples

3. Method as callback

const user = {
  name: "Ava",
  greet() {
    return "Hi " + this.name;
  }
};

const fn = user.greet;
console.log(fn()); // this is undefined in strict mode

this depends on call site.

4. Bind this

const user = {
  name: "Ava",
  greet() {
    return "Hi " + this.name;
  }
};

const bound = user.greet.bind(user);
console.log(bound());

bind fixes this to the object.

Comparison

Without

const greet = function(user) {
  return "Hi " + user.name;
};

With

const user = {
  name: "Ava",
  greet() {
    return "Hi " + this.name;
  }
};

Common Mistakes and Fixes

Using arrow for methods

Arrow functions do not have their own this.

Losing this in callbacks

Use bind or wrap in another function.

Overusing methods for data

Store data as properties, logic as methods.

Interview Questions

What is this in a method?

It refers to the object that called the method.

Why avoid arrow methods?

Arrows do not have their own this.

How do you fix this?

Use bind or call the method on the object.

Practice Problem

Practice: Create an object with a method that returns a full name.

const user = { first: "Ava", last: "Roy" };
// TODO: add fullName method

One Possible Solution

const user = {
  first: "Ava",
  last: "Roy",
  fullName() {
    return this.first + " " + this.last;
  }
};

console.log(user.fullName());

Frequently Asked Questions

What is a method?

A function stored as an object property.

Can methods use this?

Yes, this refers to the object the method is called on.

Should I use arrow functions for methods?

Usually no, because arrows do not bind this.

Try It Yourself

Try calling the method after changing the name.