7. Object-Oriented Programming
STencil has two OOP styles: class (explicit this.) and model (bare fields).
class — with this
class Account {
func init(owner, balance) { // init = constructor
this.owner = owner;
this.balance = balance;
}
func deposit(amount) {
this.balance = this.balance + amount;
}
func withdraw(amount) {
if (amount > this.balance) {
print("Insufficient funds");
return null;
}
this.balance = this.balance - amount;
}
func report() {
return this.owner + ": " + this.balance;
}
}
let a = Account("Ember", 100); // create (also: new Account("Ember", 100))
a.deposit(50);
a.withdraw(30);
print(a.report()); // Ember: 120
print(a.balance); // 120 (read a field directly)
initis the constructor, run automatically on creation.this.fieldreads/writes the object's fields.obj.method(args)calls a method;obj.fieldreads a field.- Create with
ClassName(args)ornew ClassName(args).
model — bare fields
A model declares fields with optional defaults and lets methods use field names without this.:
model Car {
marka: string
mut hiz: int = 0
init(m) {
marka = m
}
hizlan(x) {
hiz = hiz + x
print(marka + " speed: " + hiz)
}
}
let c = Car("Toyota");
c.hizlan(20); // Toyota speed: 20
c.hizlan(30); // Toyota speed: 50
Which to use?
classis explicit and familiar (like most languages).modelis shorter for data-heavy objects.
Both create objects you access with .field and .method().
Kitteniverse Studios