ES6 정리 ④

영긔·2024년 6월 30일
0

📘 ES6 JS

목록 보기
4/6
post-thumbnail

✨ Object.create()

ES5 방식
prototype, class 등이 나오기전에 쓰던 문법

var parent = { name : 'Kim', age : 50 };
var child = Object.create(parent);

console.log(child.age); //50

이렇게 작성해 child 오브젝트가 parent를 prototype으로 두게 된다.
→ 이런 방식을 사용해 상속을 구현하기도 함

var parent = { name : 'Kim', age : 50 };
var child = Object.create(parent);
child.age  = 20;

console.log(child.age); //20

이런식으로 오브젝트의 속성을 바꿀수도 있다.
→ child.age를 꺼낼때, child의 age가 정해져있을 경우(현재는 20) 그 값을 꺼내고 없을 경우 부모의 prototype을 꺼내 age를 찾아 그 값을 꺼내고 그것도 없을 경우 부모의 부모의 prototype을 꺼낸다.

child의 자식을 만들어보자

var parent = { name : 'Kim', age : 50 };
var child = Object.create(parent);
child.age  = 20;

var grandchild = Object.create(child);

console.log(grandchild.age); //20

여기서 grandchild는 child,parent의 속성을 모두 상속받는다.
이때, grandchild.age하면 20이 나온다.

🔎 Object.getPrototypeOf()

이 메서드 안에 오브젝트를 넣으면 부모 prototype을 출력
__proto__와 비슷한 역할을 해준다

✨ class

상속기능을 도와주는 문법

function Parent(){
  this.name = 'Young';
}
var child = new Parent();

이전에 작성했던 이 코드를 class를 사용해 바꿔보자

class Parent {
  constructor(){
    this.name = 'Kim'
  }
}
var child = new Parent();

constructor를 사용해 오브젝트에 값을 부여했다.

function Parent(){
  this.name = 'Kim';
  this.sayHi = function(){
    console.log('hello');
  }
}
var child = new Parent();

해당 코드를 class를 사용해 바꿔보자

class Parent {
  constructor(){
    this.name = 'Kim';
    this.sayHi = function(){ console.log('hello') }
  }
}
var child = new Parent();

앞에서와 비슷하게 바꿀수있다. child에도 sayHi메서드를 쓸 수 있다.

function Parent(){
  this.name = 'Kim';
}
Parent.prototype.sayHi = function(){ 
  console.log('hello') 
}
var child = new Parent();

해당 코드를 class를 사용해 바꿔보자

class Parent {
  constructor(){
    this.name = 'Kim';
  }
  sayHi(){ 
    console.log('hello') 
  }
}
var child = new Parent();

오브젝트에 함수를 추가하는 것처럼 작성하면 됨

🔎 파라미터 추가

class Parent {
  constructor(name, age){
    this.name = name;
    this.age = age;
  }
}

var child = new Parent('Park', 30);

이렇게 파라미터를 넣어 constructor를 만들 수 있다.

✨ extends

class를 상속한 class를 만들 때 씀

class parent{
  constructor(name){
    this.lastName = 'Song';
    this.name = name;
  }
}

class child extends parent{
  constructor(name){
    super(name);
    this.age = 26;
  }
}
var a = new child('영긔');//{ lastName : 'Song', lastName : '영긔', 나이 : 26 }

child가 parent를 상속하도록 작성했다. 이때, super를 작성하지 않으면 에러가 난다.

super : extends로 상속중인 classconstuctor() 의미

또, 부모 constructor에 name을 추가할 수 있으므로 자식 constructor에도 name이 추가되도록 해야하고, super에도 추가해야 함.
a 변수는 child로부터 새로 생성된 오브젝트. parent가 갖고있던 lastName, name, child가 갖고 있던 age를 상속받음

class parent{
  constructor(name){
    this.lastName = 'Song';
    this.name = name;
  }
  sayHi(){
    console.log('난 영긔야')
  }
}

class child extends parent{
  constructor(name){
    super(name);
    this.name = 26;
  }
}

var a = new child('영긔');

위와 같이 작성했을 때, a 오브젝트에서 sayHi()를 쓸 수 있다.
→ a 오브젝트에서 sayHi를 찾고, 없다면 child.prototype에서 sayHi가 있는지 참고, 없다면 parent.prototype에서 sayHi가 있는지를 찾는다.

🔎 class간 함수 상속

class parent{
  constructor(name){
    this.lastName = 'Song';
    this.name = name;
  }
  sayHi(){
    console.log('난 영긔야')
  }
}

class child extends parent{
  constructor(name){
    super(name);
    this.name = 26;
  }
  sayHi2(){// '난 영긔2야 난 영긔야' 출력
    console.log('난 영긔2야');
    super.sayHi();
  }
}

var a = new child('영긔');

super를 사용해서 sayHi를 불러왔다.

super의 의미: 1. constructor 안에서 쓰면 부모 classconstructor
2. prototype 함수 안에서 쓰면 부모 classprototype

✨ getter, setter

오브젝트 내의 함수들을 괄호 없이 쓸 수 있게 하고, 데이터의 무결성 보존하기 위해 쓴다.

📋 함수로 object 데이터 꺼내기

var person = {
  name : 'Kim',
  age : 30,
  nextAge(){
    return this.age + 1
  }
}

이런 코드가 있을 때, age를 변경할 때, 직접 person.age+1 하지 않고 메서드를 불러와서 값을 변경해준다.

이렇게 쓰는 이유: 오브젝트 안 데이터가 복잡할 수록 메서드 만드는 게 데이터를 꺼내기 쉽다. 또, 내부 변수를 건드리지 않아 실수를 방지

📋 함수로 object 데이터 수정

var person = {
  name : 'Kim',
  age : 30,
  setAge(age){
    this.age = age
  }
}

데이터가 손상되는 것을 방지해준다. 만약, person.setAge('30')으로 작성하면 숫자가 아니라 문자가 저장되어 데이터가 손상되나 데이터 수정메서드를 사용하면

var person = {
  name : 'Kim',
  age : 30,
  setAge(age){
    this.age = parseInt(age)
  }
}
person.setAge('30');

이렇게 문자로 저장해도 숫자로 바꿔주는 로직을 추가해 데이터 손상을 방지한다.

🔎 get, set 키워드

var person = {
  name : 'Kim',
  age : 30,
  set setAge(age){
    this.age = parseInt(age)
  }
}
person.setAge=30;

set 키워드를 사용해 등호로 값 집어넣을 수 있다. 이렇게 set이 붙은 함수를 setter라고 칭한다.

var person = {
  name : 'Kim',
  age : 30,
  get nextAge(){
    return this.age + 1  
  }
}
console.log(person.nextAge)

getter를 사용하면 소괄호 없이 값을 불러올 수 있다.

✨ 응용

💡 class, extends 사용해 구조 생성하기

개, 고양이 class를 만드는데, 개는 type, color를 지정해줄수 있고, 고양이는 개를 상속하고 age를 추가로 지정해줄수 있다.
또, 개, 고양이 오브젝트에 getMoreAge 메서드를 써 개 class로부터 생성된 오브젝트가 사용하면 에러나고, 고양이 class로부터 생성된 오브젝트가 사용하면 현재 age에 1을 더해주도록 작성할 것이다.

class Dog{
    constructor(type,color){
        this.type=type;
        this.color=color;
    }
    getMoreAge(){
        if(this instanceof Cat){//Cat class일때만 작동
            this.age++;
        }
    }
}
var dog1 = new Dog('말티즈','white');
var dog2 = new Dog('진돗개','brown');
class Cat extends Dog{
    constructor(type,color,age){
        super(type,color);
        this.age=age;
    }
}
var cat1 = new Cat('코숏','white',5);
var cat2 = new Cat('러시안블루','brown',2);

💡 get, set 활용 -1

class 이름은 Unit
(1) 모든 Unit의 인스턴스는 공격력, 체력 속성이 있으며 기본 공격력은 5, 기본 체력은 100으로 설정되어 있어야 함
(2) 모든 Unit의 인스턴스는 전투력을 측정해주는 battlePoint라는 getter가 있음
console.log( 인스턴스.battlePoint ) 이렇게 사용하면 현재 공격력과 체력을 더한 값을 콘솔창에 출력
(3) 모든 Unit의 인스턴스는 heal이라는 setter가 있음
인스턴스.heal = 50 이렇게 사용하면 체력 속성이 50 증가

class Unit {
    constructor(){
        var attack = 5;
        var hp = 100;
    }
    get battlePoint(){
        return this.attack + this.hp;
    }
    set heal(hp){
        this.hp+=parseInt(hp);
    }
}
var newOne = new Unit();
console.log(newOne.battlePoint);
newOne.heal=50;

위와 같이 작성했다. get에서 this.을 사용하는 것에 주의. 그냥 attack+hp 이렇게 작성하면 안됨

💡 get, set 활용 -2

var data = {
  odd : [],
  even : []
}

이와같은 data 오브젝트가 있을 때
(1) data 오브젝트에는 setter 역할 함수가 하나 필요
setter 함수에 1,2,3,4 이렇게 아무 자연수나 파라미터로 입력하면 홀수는 odd, 짝수는 even 이라는 속성에 array 형태로 저장
(2) data 오브젝트에는 getter 역할 함수 필요
getter 함수를 사용하면 odd, even에 저장된 모든 데이터들이 숫자순으로 정렬되어 출력
하도록 작성해보자

var data = {
    odd : [],
    even : [],
    setFunction: function(...arr){
        arr.forEach((a)=>{
            if(a%2==0){
                this.even.push(a);
            }
            else{
                this.odd.push(a);
            }
        });
    },
    get getFunction(){
        return [...this.odd, ...this.even].sort()
    }
};
data.setFunction(1,2,3,4,5);
console.log(data.getFunction);

파라미터가 2개 이상일 경우 set 키워드는 사용할 수 없다. 따라서 setFunction은 위와 같이 작성했다. ...arr를 사용해 배열로 만들어 넣어주었고, arr 배열에 반복문을 돌려 odd, even 배열에 값을 넣어주었다.
getFuncion을 통해 odd, even 배열에서 값을 가져와 한 배열로 만든 후 sort로 정렬해주었다.

🤔 주의할점: 앞에서 ...arr은 배열로 묶어주나, 뒤에서 ...this.odd 이거는 배열을 풀어주는 기능을 함
🤔 주의할점2: 반복문 부분에서 원래는

        arr.forEach(function(a){
            if(a%2==0){
                this.even.push(a);
            }
            else{
                this.odd.push(a);
            }
        });

이런식의 반복문을 작성했으나, 여기서 this는 의도한 대로의 this를 가르키지 않았다. 따라서 밖의 this를 가져와야 하므로 arrow function을 사용해 다음과 같이 수정하니 의도한 대로 동작했다.

        arr.forEach((a)=>{
            if(a%2==0){
                this.even.push(a);
            }
            else{
                this.odd.push(a);
            }
        });
profile
SKYDeveloper

0개의 댓글