객체(object)
https://sunshineyellow.tistory.com/17
[코딩앙마 외] 객체(Object)와 프로퍼티(property)
객체(Object) key와 value로 이루어질 수 있다. 1. 함수표현식 const goodCoder = function(name, age, coding) { name : 'Noran', age : 20, coding : function(){ console.log('화이팅!'); } } name : 'Noran',..
sunshineyellow.tistory.com
위 글에서 잠깐 짚고 넘어간 객체를 클래스와 함께 심화학습한다.
class Goodcoder {
//constructor
constructor(name, age) {
this.name = name;
this.age = age;
}
//method
coding() {
console.log(`${this.name}, good job!`);
}
};
//object
const noran = new Goodcoder()
클래스의 오브젝트(객체)는 new 연산자를 꼭 사용해야 한다.
Getter와 Setter
class Goodcoder {
//constructor
constructor(name, age) {
this.name = name;
this.age = age;
}
//getter
get age() {
return this._age; // call stack size 에러를 방지하기 위해 변수 앞에 _를 붙인다.
}
//setter
set age(value) {
if (value < 0) {
throw Error('나이는 정수로 작성해 주세요.');
}
this._age = value; // call stack size 에러를 방지하기 위해 변수 앞에 _를 붙인다.
}
};
//object
const noran = new Goodcoder('noran', -1) //'age는 -1이 될 수 없다.'는 설정일 때
getter는 age(오브젝트 또는 변수가 될 수 있다.)의 값을 가져오고, setter는 age의 값을 설정한다.
위 코드에서 get을 정의하는 순간, constructor 내의 this.age = age;에서 this.age는 메모리에 들어있는 데이터를 읽어오는 것이 아니라 get을 호출하게 된다.
또한 set을 정의하는 순간, constructor 내의 this.age = age;에서 = age;는 메모리에 값을 할당하는 것이 아니라 set을 호출하게 된다.
위 코드에서 나이가 0 아래로 내려갈 수 없게 하는 setter는 이런 식으로도 작성될 수 있다.
//setter
set age(value) {
this._age = value < 0 ? 0 : value;
}
출처 : 드림코딩 https://www.youtube.com/@dream-coding / MDN https://developer.mozilla.org/ko
'🟨 JavaScript > 개념' 카테고리의 다른 글
| [mdn, 드림코딩 외] 객체지향 (4) : 클래스의 상속 (sub classing) (0) | 2022.05.25 |
|---|---|
| [mdn, 드림코딩 외] 객체지향 (3) : 정적 속성과 메소드(static properties and methods) (0) | 2022.05.04 |
| [mdn, 드림코딩 외] 객체지향 (1) : 클래스(class) (0) | 2022.05.03 |
| [드림코딩 외] 콜백함수 (Callback function) (0) | 2022.04.22 |
| [드림코딩] Early return, early exit? (0) | 2022.04.21 |