TypeScript Tutorial
TypeScript Class Methods
Methods are functions that belong to a class. Call them on an object with the dot operator.
Functions that belong to a class
A method is a function written inside a class. It can use the object's fields without you passing them as extra arguments. You call it on an object: c.bump(). The object before the dot is the one the method works on.
Free functions live outside any class. Methods live on a type. That is how a Counter canbump and show without a pile of loose functions that all take a counter as the first parameter.
Write the method in the class body
Define the method inside the class. Give it a return type, the same way you would a free function. Inside the body, read and write fields through this. this.value means the valuefield of the object that received the call.
Example
class Counter {
public value: number = 0;
public bump(): void {
this.value = this.value + 1;
}
}
const c: Counter = new Counter();
c.bump();
console.log(c.value);Without this, value would look like a free variable and tsc would not treat it as the field. Write this. on every member access in a method.
Call with the dot
c.bump() runs bump on object c. Inside bump,this.value means c.value for that call. If you later have two counters, each method call uses that object's own value.
Example
class Counter {
public value: number = 0;
public bump(): void {
this.value = this.value + 1;
}
public show(): void {
console.log(this.value);
}
}
const c: Counter = new Counter();
c.bump();
c.bump();
c.show();Try it in /typescript/try. Add a second object d, set d.value = 10, call d.bump(), and print both. The two counters stay independent.
Methods can take parameters
A method is still a function. It can take arguments and return a value. The object's fields are available in addition to those parameters. add below increases value by n.
Example
class Counter {
public value: number = 0;
public add(n: number): void {
this.value = this.value + n;
}
public get(): number {
return this.value;
}
}
const c: Counter = new Counter();
c.value = 2;
c.add(5);
console.log(c.get());The object is this
this is the object before the dot. Beginners need it on every field and every other method call inside the class: this.value, this.show(). Use it also when a parameter has the same name as a field — the parameter hides the field unless you write this.value = value.
Call methods on an object, not on the class name. c.bump() is correct.Counter.bump() is not, unless you later learn static methods.
Set fields before you rely on them
bump reads this.value. The examples initialize value to0 on the field, so the object starts usable. If a field had no starter value, you would assign it in main-level code or in a constructor. Next: constructors, so the object starts valid without a separate assignment.