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