최신 프론트엔드 트렌드는 함수형 프로그래밍이 강조되고 있지만, 객체지향 프로그래밍도 알아두면 좋을 것 같다.
ES6에서 도입된 기능이다.key)와 값(value)로 구성된 프로퍼티(Property)들의 집합이다.property)method)객체 안에 프로퍼티로 정의된 함수를 메서드라고 한다.
const obj = {
f1 : function () {
console.log("hi!")
},
f2(){
console.log("hi!")
}
기존에는 f1의 형태처럼, 프로퍼티를 정의할 때와 동일하게 선언했었는데,
ES6에서는 f2와 같이 : 를 생략한 축약 표현을 사용할 수 있다.
ES6 이후의 코드를 작성할 때는 더 간결한 축약 메서드 구문을 사용하는 것이 일반적이다.
#을 사용하여 클래스 내에서만 접근 가능한 프라이빗 필드를 정의할 수 있다.class Person {
#name;
#age;
constructor(name, age) {
this.#name = name;
this.#age = age;
}
// Getter
get name() {
return this.#name;
}
get age() {
return this.#age;
}
// Setter
set name(newName) {
this.#name = newName;
}
set age(newAge) {
if (newAge > 0) {
this.#age = newAge;
}
}
}
const person = new Person('John', 30);
console.log(person.name); // "John"
console.log(person.age); // 30
person.name = 'Jane'; // setter 호출
person.age = 35; // setter 호출
console.log(person.name); // "Jane"
console.log(person.age); // 35상속
다형성
Method Overloading)Method Overriding)key : value 형식으로 나열한다.const healthObj = {
name : "달리기",
lastTime : "PM10:12",
showHealth() {
console.log(this.name + "님, 오늘은 " + this.lastTime + "에 운동을 하셨네요");
}
}
healthObj.showHealth();
const Health = function(name,healthTime) {
this.name = name;
this.healthTime = healthTime;
this.showHealth = function() {
console.log(this.name + "님, 오늘은 " + this.healthTime + "에 운동을 하셨네요");
}
}
const ho = new Health("crong", "12:12");
ho.showHealth();
const Health = class {
constructor(name, healthTime) {
this.name = name;
this.healthTime = healthTime;
}
showHealth(){
console.log(this.name + "님, 오늘은 " + this.healthTime + "에 운동을 하셨네요");
}
}
const ho = new Health("crong", "12:12");
ho.showHealth();
this 키워드를 사용하며 인스턴스 변수를 구분할 수 있다.class Example {
constructor(value) {
this.value = value; // 인스턴스 변수
}
showValue() {
let value = 10; // 로컬 변수
console.log(value); // 출력 : 로컬 변수
console.log(this.value); // 출력 : 인스턴스 변수
}
}