Classes
Objects with methods, fields, and constructors.
Declare a class with class Name { ... }. Methods inside a class omit the fun keyword: just name(args) { }. Methods may use ...rest as the last parameter to collect trailing arguments into an array.
An init method runs when you call the class like a function. Use this for the current instance.
Instance fields are set with this.field = value. Reading undefined fields looks up methods on the class.
When a reference might be nil, use **?.** optional chaining to read nested fields without crashing. See **Optional chaining**.
Class with init
Call a class like a function to create an instance. `init` sets up `this`.
class Greeter {
init(name) {
this.name = name;
}
hello() {
print "Hello, " + this.name + "!";
}
}
var g = Greeter("Rain");
g.hello();output
Hello, Rain!
Fields on instances
Store data on `this` in `init` and read it with `instance.field`.
class Box {
init(label) {
this.label = label;
}
}
var b = Box("gift");
print b.label;output
gift