Fields
- Public instance fields
- Private instance fields
- Public static fields
- Private static fields
class
The class becomes useful when you create an instance of the class. An instance is an object containing data and behavior described by the class.
(클래스는 인스턴스를 만들 때 유용하다. 인스턴스는 클래스에서 설명하는 데이터와 동작들을 포함하는 객체이다.)
constructor()
constructor is a special method in the body of a class that initializes the instance.
That's the place where you set the initial values for the fields, or do any kind of object setup.
If you don't define a constructor for the class, a default one is created. The default constructor is an empty function, which doesn't modify the instance.
()
class User {
// properties - do not depend on the constructor
age = 32;
// easy to see what the constructor does that is only about *constructing* the object
constructor(name) {
name; // => 'delilah'
this.you = name;
}
}
const user = new User('delilah');
user // User {you: 'delilah'}
you
는 public field
you
프로퍼티는 User class body 바깥에서도 접근할 수 있기 때문age
는 class field
캡슐화는 클래스 내부의 세부 정보들을 숨길 수 있는 중요한 개념이다.
캡슐화된 클래스를 사용하며느 공통 인터페이스에만 접근하고 클래스의 디테일한 부분까지 연결되지 않기 때문에, 세부 정보가 변경될 시 더 쉽게 업데이트할 수 있다.
이를 위한 방법으로 private fields
를 사용하는 것이다. 클래스의 외부에서는 private filed를 직접 변경할 수 없다.
The private fields are accessible only within the body of the class.
접미사 #
를 사용한다.
class User {
#name;
constructor(name) {
this.#name = name;
}
getName() {
return this.#name;
}
}
const user = new User('willy');
user.getName(); // 접근 가능 => 'willy'
user.#name; // 접근 불가능 => SyntaxError is thrown
클래스 자체에 필드를 정의할 수도 있다.
상수 또는 특정한 정보를 클래스에 저장하는 데 유용하다.
static
키워드를 사용한다.
class User {
static TYPE_ADMIN = 'admin';
static TYPE_REGULAR = 'regular';
// 위 TYPE_ADMIN과 TYPE_REGULAR는 static variables (정적 변수)를 정의한다.
name;
type;
constructor(name, type) {
this.name = name;
this.type = type;
}
}
const admin = new User('딜라', User.TYPE_ADMIN);
// 정적 변수를 사용하기 위해서는 [클래스명.정적변수명]과 같이 사용한다.
admin.type === User.TYPE_ADMIN; // true
정적 필드도 숨기고 싶을 때는 #필드명
과 같이 사용한다.
class User {
static #MAX_INSTANCES = 2;
static #instances = 0;
name;
constructor(name) {
User.#instances++;
if (User.#instances > User.#MAX_INSTANCES) {
console.warn('에러에러에러')
}
this.name = name;
}
}
new User('헬로');
new User('봉쥬흐');
new User('안냥'); // 에러에러에러
Methods
- Instance methods
- Getters and setters
- Static methods
class User {
name = 'Unknown';
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
const user = new User('delilah lee');
user.getName(); // => 'delilah lee'
In a class method, as well as in the constructor, this value equals to the class instance. Use this to access instance data: this.field, or even call other methods: this.method().
class User {
name = 'Unknown';
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
nameContains(str) {
return this.getName().includes(str);
}
}
const user = new User('delilah lee');
user.getName(); // => 'delilah lee'
user.nameContains('lee'); // => true
user.nameContains('willy'); // => false
nameContains(str) { ... } is a method of User class that accepts one parameter str. More than that, it executes another method of the instance this.getName() to get the user's name.
메소드를 private하게 할 수도 있다.
class User {
#name;
constructor(name) {
this.#name = name;
}
#getName() {
return this.#name;
}
nameContains(str) {
return this.#getName().includes(str);
}
}
const user = new User('delilah lee');
user.nameContains('lee'); // => true
user.nameContains('willy'); // => false
user.#getName(); // SyntaxError is thrown
getter는 필드 값을 얻을 때 실행
setter는 값을 설정할 때 실행
class User {
nameValue;
constructor(name) {
this.name = name;
}
get name() {
return this.nameValue;
}
set name(name) {
if (name === '') {
console.warn('에러에러에러')
}
this.nameValue = name;
}
}
const user = new User()
user // User {nameValue: undefined}
const user = new User('') // 에러에러에러
const user = new User('이정은')
user // User {nameValue: '이정은'} => by getter
user.name = '이윌리' // => by setter
user // User {nameValue: '이윌리'}
let obj = {
name : '이정은',
get hello() {
console.log(this.name, '겟')
return this.name + '하트';
},
set hello(value) {
console.log(this.name, '셋', value)
this.name = value;
}
}
obj
{name: '이정은'}
obj.hello
// 이정은 겟
'이정은하트'
obj.hello = '이윌리'
// 이정은 셋 이윌리
'이윌리'
obj.hello
// 이윌리 겟
'이윌리하트'
obj
{name: '이윌리'}
정적 메서드는 클래스에 직접 연결된 함수이다. 따라서, 클래스의 인스턴스가 아니라, 클래스와 관련된 로직을 가진다.
static
메소드명으로 사용한다.
class User {
static takenNames = [];
static isNameTaken(name) {
return User.takenNames.includes(name);
}
name = 'Unknown';
constructor(name) {
this.name = name;
User.takenNames.push(name);
}
}
const user = new User('Jon Smith');
const user = new User('John Lee');
User.takenNames // ['Jon Snow', 'John Lee']
User.isNameTaken('Jon Smith'); // true
Inheritance
- Parent constructor: super() in constructor()
- Parent instance: super in methods
class Child extends Parent { }
: child class는 parent class로부터 constructor, fields, methods를 상속받는다.
단, 부모클래스의 private members는 자식클래스로 상속되지 않는다.
class User {
name;
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
class ContentWriter extends User {
arr = [];
}
const writer = new ContentWriter('willy');
writer.name; // => 'willy'
writer.getName(); // => 'willy'
writer.arr; // => []
ContentWriter 클래스는 User 클래스로부터,
name
라는 field와 + constructor
constructor와 + getName()
이라는 method를 상속받았고 + arr
라는 field를 새로 선언했다.
자식클래스에서 부모클래스의 constructor를 call하고 싶으면, 자식클래스의 constructor 내부에서 super()
라는 special function을 사용해야 한다.
자식클래스 내부의 super(name)
는 부모클래스의 생성자를 실행한다.
class User {
name;
constructor(name) {
this.name = '이정으니';
}
getName() {
return this.name;
}
}
class Child extends User {
constructor(name) {
super(name);
}
}
const dd = new Child();
dd // Child {name: '이정으니'}
// name: "이정으니" [[Prototype]]: User
자식클래스에서 부모클래스의 method에 접근하고 싶으면, super
를 사용한다.
class User {
name;
constructor(name) {
this.name = '시바브라더';
}
getName() {
return this.name;
}
}
class Child extends User {
posts = [];
constructor(name, posts) {
super(name);
this.posts = posts;
}
getName() {
const rename = super.getName();
console.log(rename, '리네임')
if (rename === '') {
return 'Unknwon';
}
return rename;
}
}
const dd = new Child();
dd // Child {name: '시바브라더', posts: undefined}
const dd = new Child('', 'you are')
dd // Child {name: '시바브라더', posts: 'you are'}
dd.getName('') // '시바브라더'
user instanceof User (object instanceof Class)
user 객체가 User 클래스의 인스턴스인지 아닌지를 구별한다. -> return boolean