👀 자바스크립트에서 class 문법에 public, private 필드를 적용하는 것은 표준 자바스크립트에 제안된, 아직은 실험적인 기능입니다.
자바스크립트의 퍼블릭 필드는 외부에서 클래스로 접근이 가능하고 인스턴스로도 접근이 가능합니다.
크게 Public static field와 Public instance field로 나뉘어 볼 수 있습니다.
Public static field
class Rabbit {
static name = 'name is only value'
}
console.log(Rabbit.name) ✔
// expected output: "static field"
class ParentClass {
static baseField = 'base field' ✔
}
class ChildClass extends ParentClass {
static subField = 'sub class field'
}
console.log(ChildClass.subField)
// expected output: "sub class field"
console.log(ChildClass.baseField) ✔ 자식 클래스에서 부모 클래스의 baseField 접근 가능!
// expected output: "base field"
Public instance field
class Rabbit {
static name = 'name is only value'
legs = 2 // 토끼 다리는 모두 2개이길 원한다
}
const instance = new Rabbit()
console.log(instance.legs)
// expected output: 2
Object.defineProperty()에 추가됨const PREFIX = 'prefix'
class Rabbit {
[`${PREFIX}Field`] = 'prefixed field'
}
const instance = new Rabbit()
console.log(instance.prefixField)
// expected output: "prefixed field"
class Rabbit {
leg = 2
haveLegs() {
return this.msg
}
}
class childRabbit extends Rabbit {
childHaveLegs() {
return super.haveLegs()
}
}
const instance = new childRabbit()
console.log(instance.childHaveLegs())
// expected output: 2
자바스크립트의 프라이빗 필드는 외부에서 클래스로 접근이 불가능하고 인스턴스로도 접근이 불가능합니다.
크게 Private static field와 Private instance field로 나뉘어 볼 수 있습니다.
Private static field
class Rabbit {
private static age = 0
}
console.log(Rabbit.age) ❌
// expected output: roperty 'age' does not exist on type 'typeof Rabbit'
class Rabbit {
private static age = 0;
constructor() {
Rabbit.age = 1; ⭕
}
run() {
console.log(Rabbit.age); ⭕
}
}
console.log(Rabbit.age); ❌
// Property 'age' is private and only accessible within class 'Rabbit'
Private instance field
class Rabbit {
private age = 0;
constructor() {
this.age = 0;
}
run() {
if (this.age > 15) {
console.log('뛸 수 없습니다.');
}
}
}
const instance = new Rabbit();
instance.age === 0; ❌
// Property 'age' is private and only accessible within class 'Rabbit'