PROGRAMMING-CONCEPTS

This / Self: Definition, Purpose, and Examples

Many programming languages include a built-in keyword — such as this in JavaScript or self in Python and Swift — that gives methods access to the specific object they belong to. It connects a function to the data stored inside that instance, letting the method read or update state. Even though all three languages rely on the same idea, each one handles it differently.


What This/Self Refers To

Inside a method, this/self always points to the current instance.

It lets you:

  • read stored values
  • update internal state
  • call other methods on the same object

Without this/self, methods would have no way of knowing which object they’re operating on.


This in JavaScript and TypeScript

JavaScript’s this depends on how a function is called, not where it was defined. This behavior is flexible but sometimes surprising.


A Simple Method Using This

class Book {
  constructor(title, price) {
    this.title = title;
    this.price = price;
  }

  label() {
    return `${this.title} - $${this.price}`;
  }
}

const novel = new Book("The Last Orchard", 18);
novel.label(); // "The Last Orchard - $18"

Here, this.title and this.price belong to the novel instance.

If you create five different books, each one keeps its own data.


Why Arrow Functions Change This

Arrow functions don’t create their own this.

They capture it from the surrounding scope.

class Timer {
  startTime = 0;

  start = () => {
    this.startTime = Date.now();
  };
}

Using an arrow function for start keeps the correct this when the method is used as a callback.


Losing This When Passing Methods Around

const shape = {
  sides: 4,
  show() {
    console.log(this.sides);
  }
};

const fn = shape.show;
fn(); // undefined in strict mode

Pulling the method out of the object breaks the link between the function and the instance.

Three tools reconnect them:

shape.show.bind(shape)();   // 4
shape.show.call(shape);     // 4
shape.show.apply(shape);    // 4
  • bind creates a new function with a fixed this
  • call runs the function immediately with a chosen this
  • apply works like call but takes arguments as an array

This trio is essential for managing context in JavaScript.


Self in Python

Python uses self explicitly. It is simply the first parameter of any instance method.

Python automatically passes the instance into self during a method call.

class Product:
    def __init__(self, price):
        self.price = price

    def apply_discount(self, percent):
        self.price *= (1 - percent / 100)

Calling:

item = Product(120)
item.apply_discount(25)

The instance (item) becomes the value of self.

There’s no guesswork — Python’s behavior is completely predictable.


Self in Swift

Swift’s self behaves much like Python’s but appears only when needed.

class Player {
    var score: Int

    init(score: Int) {
        self.score = score // required due to name conflict
    }

    func add(points: Int) {
        score += points    // self optional here
    }
}

Swift requires self inside closures to make access explicit:

class Stopwatch {
    var elapsed = 0.0

    func begin() {
        Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { _ in
            self.elapsed += 1.0
        }
    }
}

This prevents accidental memory cycles and clarifies ownership.


Why These Keywords Matter

Methods need a way to refer to the instance they belong to.

This/self makes it possible to write code that:

  • updates internal data
  • coordinates multiple methods
  • keeps each object’s state separated from others

Whether it’s a product, a component, a timer, or a piece of UI state, all object-oriented programming relies on this/self to work properly.


Practical Examples and Why They Work


Example 1: Inventory Update (Python)

class InventoryItem:
    def __init__(self, name, count):
        self.name = name
        self.count = count

    def restock(self, amount):
        self.count += amount

Calling:

pen = InventoryItem("Pen", 30)
pen.restock(10)

self.count updates only that specific item, not every InventoryItem you create.


Example 2: Audio Player Actions (JavaScript)

class AudioPlayer {
  volume = 50;

  increase() {
    this.volume = Math.min(100, this.volume + 5);
  }
}

const player = new AudioPlayer();
player.increase(); // this.volume becomes 55

The method modifies the correct player instance.

If you create several players, each one controls its own volume.


Example 3: Swift UI Model

class ProfileViewModel: ObservableObject {
    @Published var username = "guest"

    func update(to name: String) {
        self.username = name
    }
}

When the UI re-renders, SwiftUI pulls the correct value associated with that instance.


Common Mistakes

In JavaScript: Forgetting how this is bound

Passing a method into a callback or storing it in a variable often disconnects this.

In Swift: Using self unnecessarily

Swift aims for readable code. Excessive self adds noise.

In Python: Shadowing names

If a parameter has the same name as a property, self becomes essential for clarity.

Assuming languages behave the same

JavaScript’s dynamic this has nothing in common with Python's explicit self.


Summary

This/self connects a method to the instance it belongs to.

JavaScript’s this shifts based on how the function is called, making tools like bind, call, and apply essential.

Python uses a simple explicit approach, passing the instance directly into self.

Swift blends clarity and safety, requiring self only when it improves readability or prevents bugs.

These keywords are the foundation that lets objects keep their own state and behavior. Once you understand how this/self behaves in each language, writing reliable object-oriented code becomes far more intuitive.

Learn to Code for Free
Start learning now
button icon
To advance beyond this tutorial and learn to code by doing, try the interactive experience of Mimo. Whether you're starting from scratch or brushing up your coding skills, Mimo helps you take your coding journey above and beyond.

Sign up or download Mimo from the App Store or Google Play to enhance your programming skills and prepare for a career in tech.

Reach your coding goals faster