implementing instance initializers

This commit is contained in:
2024-08-31 11:32:05 +02:00
parent b522f05c8c
commit b839d67cea
10 changed files with 95 additions and 17 deletions

View File

@ -0,0 +1,14 @@
class CoffeeMaker {
init(coffee) {
this.coffee = coffee;
}
brew() {
print "Enjoy your cup of " + this.coffee;
// No reusing the grounds!
this.coffee = nil;
}
}
var maker = CoffeeMaker("coffee and chicory");
print maker;
maker.brew();

View File

@ -0,0 +1,12 @@
class Brunch {
bacon() {
print "calling bacon()";
}
eggs() {
print "calling eggs()";
}
}
var brunch = Brunch();
print brunch;
brunch.bacon();

View File

@ -1,8 +1,4 @@
class Brunch {
bacon() {}
eggs() {}
init(food, drink) {}
}
var brunch = Brunch();
print brunch;
brunch.bacon();
Brunch("eggs", "coffee");

View File

@ -0,0 +1,17 @@
class Brunch {
var food;
var drink;
init(food, drink) {
this.food = food;
this.drink = drink;
}
fun get_recipe() {
return this.food + " " + this.drink;
}
}
var instance = Brunch("eggs", "coffee");
print instance;
print instance.get_recipe();