⚙️ Przeciążanie operatorów

Klasy mogą definiować własne zachowanie dla operatorów.

Przykład: Vector

class Vector { init(x, y) { this.x = x; this.y = y; } operator +(other) { return Vector(this.x + other.x, this.y + other.y); } operator -(other) { return Vector(this.x - other.x, this.y - other.y); } operator *(scalar) { return Vector(this.x * scalar, this.y * scalar); } operator ==(other) { return this.x == other.x && this.y == other.y; } } let v1 = Vector(1, 2); let v2 = Vector(3, 4); let sum = v1 + v2; // Vector(4, 6) let scaled = v1 * 3; // Vector(3, 6) print(v1 == v2); // false

Dostępne operatory

Operator Metoda
+operator +(other)
-operator -(other)
*operator *(other)
/operator /(other)
%operator %(other)
==operator ==(other)
!=operator !=(other)
<operator <(other)
>operator >(other)