Object Methods and Object Behavior

Course: JavaScript Intermediate

Lesson 6: Object Methods and Object Behavior

Level

Intermediate

Estimated Reading Time

10–15 minutes

Goal

By the end of this lesson, the learner will be able to:

  • Define methods on objects using both traditional and shorthand syntax
  • Explain what this refers to inside an object method
  • Use object methods to encapsulate behavior alongside data

Frontend Development Context

Objects in JavaScript do more than hold data — they can also hold behavior in the form of methods. A user object might have a getDisplayName() method. A cart object might have an addItem() method. Grouping related data and behavior together in objects is one of the most common patterns in frontend JavaScript, especially before frameworks introduce components.

Understanding how this works inside object methods is critical. When a method reads this.name or this.items, it is reading a property on the object the method belongs to. But this can behave unexpectedly when methods are extracted from objects or passed as callbacks — knowing why helps you write object code that behaves predictably.

Explanation

A method is simply a function stored as a property on an object. You can define it with a traditional function expression, or with the modern shorthand syntax that omits the colon and the function keyword. Both produce the same result, but shorthand is cleaner and is now the standard style.

Inside a method, this refers to the object the method was called on. If you call user.greet(), then inside greet, this is user. This allows methods to read and modify other properties on the same object without those properties being explicitly passed as arguments.

However, this is determined by how a function is called, not where it is defined. If you extract a method from an object and call it as a plain function, this loses its reference to the object. This is one of the most common sources of bugs when working with object methods and callbacks.

JavaScript objects are also dynamic — you can add properties and methods after the object is created. This is useful for extending objects at runtime, though it is better to define the full interface upfront when possible.

Object.keys(), Object.values(), and Object.entries() are built-in methods that let you iterate over an object's properties. These are useful for rendering object data in the UI, validating forms, or converting objects for API requests.

Code Example

This example defines an object with data and methods, shows shorthand syntax, and demonstrates this inside a method.

const userProfile = {
  username: "alex_dev",
  score: 240,
  level: "Intermediate",

  // Shorthand method syntax
  getDisplayName() {
    return `@${this.username}`;
  },

  getSummary() {
    return `${this.getDisplayName()} — Level: ${this.level}, Score: ${this.score}`;
  },

  addPoints(points) {
    this.score += points;
    console.log(`New score: ${this.score}`);
  }
};

console.log(userProfile.getDisplayName()); // "@alex_dev"
console.log(userProfile.getSummary());     // "@alex_dev — Level: Intermediate, Score: 240"
userProfile.addPoints(50);                 // "New score: 290"

// Iterating over object properties
Object.entries(userProfile).forEach(([key, value]) => {
  if (typeof value !== "function") {
    console.log(`${key}: ${value}`);
  }
});

Code Explanation

userProfile is an object with three data properties (username, score, level) and three methods. The methods use shorthand syntax — no function keyword, no colon before the body.

Inside getDisplayName(), this.username reads the username property of the same object. Inside getSummary(), this.getDisplayName() calls another method on the same object — methods can call each other through this.

addPoints modifies this.score directly. Because this refers to userProfile when called as userProfile.addPoints(50), the score property is updated on the object itself.

The Object.entries loop at the bottom iterates over all key-value pairs and skips functions. This pattern is useful for rendering object data without accidentally calling methods as if they were strings.

Pattern Highlights

Positive Pattern: Use method shorthand syntax inside object literals. It is more concise and signals clearly that the property is a method, not a plain value.

⚠️ Neutral Note: Methods that call other methods via this work correctly when called on the object. If getSummary were extracted and called standalone, this would not point to userProfile and the call would fail.

Negative Pattern: Do not use arrow functions as object methods when you need this to refer to the object. Arrow functions capture this from the outer scope (usually undefined or the global object in an object literal context), so this.username would not work.

Common Mistakes

Mistake 1: Using an arrow function as a method that needs this

Defining an object method as an arrow function breaks this.

const profile = {
  name: "Sam",
  greet: () => {
    return `Hello, ${this.name}`; // 'this' is not the profile object
  }
};
console.log(profile.greet()); // "Hello, undefined"

Arrow functions inherit this from the surrounding lexical scope, not from the object. Use regular method shorthand instead.

Mistake 2: Extracting a method and losing this

Storing a method in a variable and calling it as a plain function.

const profile = {
  name: "Taylor",
  greet() { return `Hi, ${this.name}`; }
};

const fn = profile.greet;
fn(); // "Hi, undefined" — this is no longer profile

When fn is called as a plain function, this is no longer profile. To preserve context, use .bind(profile) or call it as profile.greet().

Mistake 3: Forgetting that object properties are shared references

Nesting an object or array as a property value means all references point to the same structure.

const defaults = { tags: ["js"] };
const lesson = { ...defaults };
lesson.tags.push("advanced");
console.log(defaults.tags); // ["js", "advanced"] — original was mutated

Spread copies top-level properties by value, but nested objects and arrays are still references. Use deep copies when you need independent nested data.

Quick Recap

  • Object methods are functions stored as properties and defined using shorthand syntax in modern JavaScript
  • Inside a method, this refers to the object the method was called on
  • this is determined by how a function is called — extracting a method and calling it as a plain function loses the this reference
  • Object.keys(), Object.values(), and Object.entries() let you iterate over an object's data properties programmatically

Ready to test your understanding? Take the quiz to reinforce what you learned.

© 2026 Ant Skillsv.26.07.07-23:01