public, private, setter, getter // 자바스크립트 클래스 문법에 대해..
1. public
-> writable, enumerable, configurable( 해당 속성의 값을 변경할 수 있고, 열거가 가능하며, 속성 재변경을 방지하는 특성)
-> public 필드는 생성자나 함수를 통해 동적으로 필드를 생성할 수 있다.
class Rectangle {
height = 0;
width;
constructor(height, width) {
this.height = height;
this.width = width;
}
}
2. Private
-> 클래스 외부나 서브 클래스에서 접근할 수 없다.
class CoffeeMachine {
#waterLimit = 200;
#checkWater(value) {
if (value < 0) throw new Error("물의 양은 음수가 될 수 없습니다.");
if (value > this.#waterLimit) throw new Error("물이 용량을 초과합니다.");
}
}
let coffeeMachine = new CoffeeMachine();
// 클래스 외부에서 private에 접근할 수 없음
coffeeMachine.#checkWater(); // Error
coffeeMachine.#waterLimit = 1000; // Error
1) 한 클래스 내에서 public 프로퍼티와 동일한 이름의 private 프로퍼티를 가질 수 있다.
2) getter 와 setter 를 사용하는 방법이 있다.
class CoffeeMachine {
#waterAmount = 0;
get waterAmount() {
return this.#waterAmount;
}
set waterAmount(value) {
if (value < 0) throw new Error("물의 양은 음수가 될 수 없습니다.");
this.#waterAmount = value;
}
}
let machine = new CoffeeMachine();
machine.waterAmount = 100;
alert(machine.#waterAmount); // Error
3) private 필드와 메서드는 상속되지 않는다.
4) 모든 Private 필드는 소속된 클래스에 고유한 스코프를 갖는다.
class Human {
#age = 10;
getAge() {
return this.#age;
}
}
class Person extends Human {
getFakeAge() {
return this.#age - 3; // Property '#age' is not accessible outside class 'Human' because it has a private identifier.
}
}
3. Getter와 Setter
1) 함수를 속성처럼 보이게 해서 복잡성을 숨기는 방법.
class Coupon {
constructor (price, expiration) {
this.price = price;
this.expiration = expiration || '2주'
}
get getPriceText () {
return `$${this.price}`
}
get getExpirationMessage () {
return `이 쿠폰은 ${this.expiration}후에 만료됩니다.`
}
set halfPrice(price) {
this.price = price / 2
}
}
const coupon = new Coupon(5)
coupon.halfPrice = 20;
console.log(coupon.price) // 10
console.log(coupon.getPriceText) // $10
-> get함수로 getPriceText() 와 getExpirationMessage() 를 설정.
-> set함수로 halfPrice() 를 설정.
-> set함수에는 변수처럼 값을 할당할 수 있다.
-> get의 경우 coupon.getPriceText로 접근해 뒤에 괄호를 붙이지않아 속성처럼 보이게 할 수 있다.(마지막 줄)
2) get,set함수가 속성명과 곂칠경우 무한루프에 빠질 수 있다.
class Coupon {
constructor (price, expiration) {
this.price = price;
this.expiration = expiration || '2주'
}
get price() {
return this.price;
}
set price(price) {
this.price = `$ ${price}`
}
}
const coupon = new Coupon(5)
// result
RangeError: Maximum call stack size exceeded
-> 인스턴스 생성과 동시에 에러발생.
-> 이럴 경우, 코드 컨벤션에 따라 속성명 앞에 밑줄 _을 입력해 속성이 비공개라는 점을 표시한다.
class Coupon {
constructor (price, expiration) {
this._price = price;
this.expiration = expiration || '2주'
}
get price() {
return this._price;
}
set price(price) {
const newPrice = price.toString().replace(/[^\d]/g,'')
this._price = parseInt(newPrice, 10);
}
}
const coupon = new Coupon(5)
coupon.price = '15a'
console.log(coupon.price) // 15
[출처]
https://mine-it-record.tistory.com/470
[ES6+] 클래스(Class)문법에 대하여
ES6부터는 자바스크립트 또한 Class문법을 사용할 수 있게 되었다. 자바스크립트에서의 Class는 함수라는 것을 알아두고 클래스(Class)문법에 대해 하나씩 알아가보자. 1. 클래스(Class) 정의 1-1. 클래
mine-it-record.tistory.com
https://ui.toast.com/weekly-pick/ko_20200312
은닉을 향한 자바스크립트의 여정
ECMAScript 클래스 필드(class field) 명세중에 `Private field` 즉 `Private Property` (이하 Private 속성) 가 있다. 클래스 필드 스펙은 Stage 3(Candidate)까지 올랐으니 아마 곧 Stage 4(Finished)를 거쳐 표준 스펙이 될
ui.toast.com
[ES6] Class 사용하기(2) - get,set, 클래스에서 generator구현, bind(),화살표함수 , iterable 클래스
안녕하세요 이번 포스팅의 내용입니다.지난 게시물의 소스코드를 사용합니다. (Ctrl + Click)get함수로 getPriceText() 와 getExpirationMessage() 를 설정했고,set함수로 halfPrice() 를 설정했습니다.set함수에는
velog.io
https://eyabc.github.io/Doc/dev/core-javascript/%ED%81%B4%EB%9E%98%EC%8A%A4.html#class-syntax
ES6 클래스 | 재미있는 기억만 남기자
ES6 클래스 생성자 함수를 더 깔끔한 문법으로 정의 가능 Syntatic Sugar prototype 기반 상속을 보다 명료하게 사용할 수 있는 문법을 제공 다른언어의 Class 문법과 생김새는 비슷함 BUT 내부 동작은 다
eyabc.github.io
'코딩 > Javascript' 카테고리의 다른 글
[TIL] 23.01.10 - 자바스크립트에서 ?? 활용 (0) | 2023.01.10 |
---|---|
[TIL] 22.12.22 - Vue3 약관동의 체크박스 (0) | 2022.12.22 |
[스터디] 3일차(2022.12.17) - 얕은 복사, 깊은 복사 (0) | 2022.12.19 |
[스터디 2일차] - 일급함수, 고차함수 특징 알아보기 (0) | 2022.12.10 |
[스터디] 22.12.03 - 자료구조 알아보기(Array, Set, Object) (0) | 2022.12.02 |