CodeBlanks Logo Icon CodeBlanks

Methods

Learn to add methods to classes.

Class methods

You define behavior by adding methods to a class. A method is written like a function in the class body and can access the instance's fields with this. It is called with a dot on the instance.

class Greeter {
  name: string;
  constructor(name: string) {
    this.name = name;
  }
  greet(): string {
    return "Merhaba, " + this.name;
  }
}
const g = new Greeter("Ada");
console.log(g.greet());

Calling methods

Methods are called with a dot on the instance: g.greet(). Inside the method, this refers to the instance it was called on. So when g.greet() is called, this.name is g's name field.

const g = new Greeter("Ada");
console.log(g.greet());  // "Merhaba, Ada"

Practice Rectangle class and area method

Define a Rectangle class with width: number and height: number fields. Add a constructor that takes both parameters. Write an area(): number method that returns this.width * this.height. Create a new Rectangle(4, 5), call area(), and print the result.

Starter code

index.ts
// Rectangle sınıfı tanımla (genişlik ve yükseklik)
// constructor ile her iki alanı al
// alan hesaplayan metot yaz (width * height)
// yeni Rectangle oluştur, çağır ve yazdır

Sample solution

index.ts
class Rectangle {
  width: number;
  height: number;
  constructor(width: number, height: number) {
    this.width = width;
    this.height = height;
  }
  area(): number {
    return this.width * this.height;
  }
}

const r = new Rectangle(4, 5);
console.log(r.area());

Expected output

20

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does this refer to in a class method?

  • The global object
  • The class itself
  • The parent class
  • The instance that was called Correct answer

Explanation: this refers to the instance the method was called on. You access that instance's name field with this.name. It is not the class itself or the parent class.

2 Complete the method return

Question
greet(): string {
    return "Merhaba, " + ____;
  }
Answer
greet(): string {
    return "Merhaba, " + this.name;
  }

Explanation: Inside a method you access the instance's name field with this.name. name is not defined, this gives the object itself, and Greeter.name is a static access (which does not exist).

3 Method parts

Term Meaning
greet() Method definition
this.name Instance field access
g.greet() Method call
: string Return type

All lessons in Intermediate