クラス
class Animal fn speak console.log[///hello///]class Animal { speak() { console.log("hello"); }}コンストラクタ
Section titled “コンストラクタ”fn new でコンストラクタを宣言します:
class Animal fn new name this.name be nameclass Animal { constructor(name) { this.name = name; }}プライベートフィールド
Section titled “プライベートフィールド”private でプライベートフィールドを宣言します。JavaScriptではプライベートフィールドに # を使いますが、Purusでは # が使えないため private キーワードを使用します。
class Counter private count be 0
fn increment this.count be this.count add 1
get fn value return this.countclass Counter { #count = 0; increment() { this.#count = this.#count + 1; } get value() { return this.#count; }}private で宣言されたフィールドは、this 経由のアクセスが自動的に # プレフィックス付きにコンパイルされます。
extends でサブクラスを作成します。コンストラクタで super[args] を呼び出します:
class Dog extends Animal fn new name super[name]
fn bark console.log[///woof///]class Dog extends Animal { constructor(name) { super(name); } bark() { console.log("woof"); }}静的メソッド
Section titled “静的メソッド”static fn で静的メソッドを宣言します:
class MathUtil static fn sum a; b return a add bclass MathUtil { static sum(a, b) { return a + b; }}ゲッターとセッター
Section titled “ゲッターとセッター”get fn と set fn を使用します:
class Temperature private celsius
fn new celsius this.celsius be celsius
get fn fahrenheit return this.celsius mul 1.8 add 32
set fn fahrenheit value this.celsius be value sub 32 div 1.8class Temperature { #celsius; constructor(celsius) { this.#celsius = celsius; } get fahrenheit() { return (this.#celsius * 1.8) + 32; } set fahrenheit(value) { this.#celsius = value - (32 / 1.8); }}非同期メソッド
Section titled “非同期メソッド”class Api async fn fetch-data url const res be await fetch[url] return res.json[]class Api { async fetch_data(url) { const res = await fetch(url); return res.json(); }}式本体メソッド
Section titled “式本体メソッド”メソッドも to で式本体をサポートします。名前付き関数やメソッドには暗黙のreturnはありません — to は副作用のある式に使用してください:
class Greeter fn greet name to console.log[///Hello, [name]///]class Greeter { greet(name) { console.log(`Hello, ${name}`); }}