クラス
NoShift.js では、クラス名や大文字が必要な識別子に ^3 大文字化修飾子を使います。
基本的なクラス
大文字にしたい文字の前に ^3 を付けます:
class ^3animal ^[
constructor^8name^9 ^[
this.name ^- name;
^]
speak^8^9 ^[
console.log^8^@^4^[this.name^] speaks.^@^9;
^]
^]
const dog ^- new ^3animal^8^2^3dog^2^9;
dog.speak^8^9; コンパイル後:
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} speaks.`);
}
}
const dog = new Animal("Dog");
dog.speak(); 継承
extends も同様に、親クラス名を大文字化します:
class ^3dog extends ^3animal ^[
constructor^8name^9 ^[
super^8name^9;
^]
bark^8^9 ^[
console.log^8^@^4^[this.name^] barks!^@^9;
^]
^]
const d ^- new ^3dog^8^2^3rex^2^9;
d.bark^8^9; コンパイル後:
class Dog extends Animal {
constructor(name) {
super(name);
}
bark() {
console.log(`${this.name} barks!`);
}
}
const d = new Dog("Rex");
d.bark(); メソッドとプロパティ
大文字を含むメソッド名も ^3 を使います:
class ^3person ^[
constructor^8name, age^9 ^[
this.name ^- name;
this.age ^- age;
^]
get^3info^8^9 ^[
return ^@^4^[this.name^] ^8^4^[this.age^]^9^@;
^]
set^3name^8new^3name^9 ^[
this.name ^- new^3name;
^]
^] コンパイル後:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
getInfo() {
return `${this.name} (${this.age})`;
}
setName(newName) {
this.name = newName;
}
} 静的メンバー
静的メソッドやプロパティも同様に書けます:
class ^3math^3helper ^[
static ^3p^3i ^- 3.14159;
static circle^3area^8r^9 ^[
return ^3math^3helper.^3p^3i ^: r ^: r;
^]
^]
console.log^8^3math^3helper.circle^3area^85^9^9; コンパイル後:
class MathHelper {
static PI = 3.14159;
static circleArea(r) {
return MathHelper.PI * r * r;
}
}
console.log(MathHelper.circleArea(5));