JS this Keyword

JavaScript Object Methods and the "this" Keyword

Objects are usually created to represent entities of the real world, like users, orders, products, and so on:

User Object Example

let user = {
  name: "John",
  age: 30
};
console.log(user);

In the real world, a user can act: they can select something from a shopping cart, log in, log out, etc.

In JavaScript, these actions are represented by functions attached to object properties.


1. What are Object Methods?

For a start, let’s teach our user to say hello. We can do this by assigning a function to a property of the object.

Basic Method Example

let user = {
  name: "John",
  age: 30
};

// Assigning a function to the property user.sayHi user.sayHi = function() { console.log("Hello!"); };

// Calling the method user.sayHi(); // Outputs: Hello!

Here we’ve just used a Function Expression to create a function and assign it to the user.sayHi property. Then we can call it as user.sayHi(). The user can now speak!

A function that is a property of an object is called its "method". So, here we’ve got a method sayHi of the object user.

Object-Oriented Programming (OOP): When we write our code using objects to represent entities, that’s called object-oriented programming. OOP is an entire paradigm of its own, focusing on how to choose the right entities and organize the interaction between them to build large, scalable applications.


2. Method Shorthand Syntax

There exists a shorter, cleaner syntax for defining methods inside an object literal.

Method Shorthand Example

// The traditional way
let user1 = {
  sayHi: function() {
    console.log("Hello from user1");
  }
};

// The Shorthand way (preferred!) let user2 = { sayHi() { // same as "sayHi: function(){...}" console.log("Hello from user2"); } };

user1.sayHi(); user2.sayHi();

As demonstrated, we can omit the word function and just write sayHi(). In almost all cases, the shorter syntax is preferred because it is easier to read.


3. The this Keyword in Methods

It is very common that an object method needs to access the information stored inside the object to do its job. For instance, the code inside user.sayHi() may need to know the name of the user.

To access the object from within a method, we use the this keyword.

The value of this is the object "before the dot"—the one used to call the method.

Using `this` Example

let user = {
  name: "John",
  age: 30,

sayHi() { // "this" is the "current object" (user) console.log(this.name); } };

user.sayHi(); // Outputs: John

Why not just use the outer variable name?

Technically, you could access the object without this, by referencing it via its outer variable name (e.g., user.name instead of this.name).

But such code is unreliable! If we decide to copy user to another variable (e.g., let admin = user;) and overwrite the original user variable with something else, the method will look at the wrong place and throw an error. Using this ensures the method always references the correct object that called it.


4. this is Not Bound in JavaScript

In JavaScript, the this keyword behaves differently than in most other programming languages. It can be used in any function, even if it’s not a method of an object!

The value of this is evaluated during run-time, depending on the context of how the function was called.

For instance, here the exact same function is assigned to two different objects and has a different this value in each call:

Unbound `this` Example

let user = { name: "John" };
let admin = { name: "Admin" };

function sayHi() { console.log(this.name); }

// Use the same function in two objects user.f = sayHi; admin.f = sayHi;

// These calls have different this values! // "this" is the object "before the dot" user.f(); // Outputs: John (this == user) admin.f(); // Outputs: Admin (this == admin)

The Golden Rule: If obj.f() is called, then this is obj during the execution of f.

Calling without an object: this == undefined

If you call a function that uses this without any object context (e.g., just calling sayHi()), this will be undefined in strict mode. If you try to access this.name, you will get a TypeError. (In non-strict mode, it defaults to the global window object, which is historically a source of many bugs!)


5. Arrow Functions have no this

Arrow functions are very special: they do not have their "own" this.

If you reference this inside an arrow function, it simply takes this from the outer "normal" function context.

For instance, here the arrow() function uses this from the outer user.sayHi() method:

Arrow Functions and `this`

let user = {
  firstName: "Ilya",
  sayHi() {
    // The arrow function doesn't have its own "this"
    // So it uses the "this" of the sayHi() method!
    let arrow = () => console.log(this.firstName);
    arrow();
  }
};

user.sayHi(); // Outputs: Ilya

This is an incredibly useful feature! Often, we actually do not want an inner function to have a separate this. We just want it to take this from the outer context (like reading a property from the object we are currently working in).


Summary


Exercise

?

In JavaScript, how is the value of this determined when a normal method is called like user.sayHi()?