멋쟁이사자처럼 프론트엔드 스쿨 2기 34_Day

aydennote·2022년 5월 18일
0
post-thumbnail

📖 오늘 학습 뽀인트!

  1. 생성자 함수
    1-1 사용자 정의 패턴
    1-2 모듈 패턴
    1-3 모듈 패턴 + 사용자 정의 패턴

  2. 클래스
    2-1 클래스 상속
    2-2 비공개(private) property

1. 생성자 함수

1-1 사용자 정의 패턴

function PersonType() {
	this.age = 35;
}
PersonType.prototype.getAge = function () {
     return this.age;
};
const person2 = new PersonType();
console.log(person2.getAge());        // 35
person2.age=50;
console.log(person2.age);             // 50

이전 게시물에 포스팅한 생성자 함수 패턴은 사용자 정의 패턴으로 외부에서 데이터를 쉽게 관리할 수 있다.

1-2 모듈 패턴

function Person() {
        let age = 15;
        return {
          getAge: function () {
            return age;
          },
          setAge: function (data) {
            age = data;
          },
        };
      }        
const person = Person();
console.log(person.getAge());      // 15
console.log(person.age);           // undefined
person.setAge(40);                 
console.log(person.getAge());      // 40

중요한 정보를 보호하기 위해 클로저 공간으로 만들어 관리하는 패턴이다.
즉, age변수에 외부에서 바로 접근이 불가능하고 get, set 메서드를 통해 데이터를 관리한다.

1-3 모듈 패턴 + 사용자 정의 패턴

function PersonType2() {
     let age = 25;
     function innerPersonType() {}
     innerPersonType.prototype.getAge = function () {
       return age;
     };
     return innerPersonType;
   }
   const Person3 = new PersonType2();
   const person3 = new Person3();
   console.log(person3.getAge());          // 25
   console.log(person3.age);               // undefined

모듈 패턴과 마찬가지로 person3.age 로 직접 값에 접근하거나 할당 할 수 없다.

2. 클래스

class SayName {
    constructor(name) {
        this.name = name;
    }
    sayMyName() {
        console.log(`제 이름은 ${this.name}입니다.`);
    }
}
const result = new SayName('ayden');
result.sayMyName()                // 제 이름은 ayden입니다.

생성자 함수로 인스턴스를 만들어 사용한 것과 같이 클래스로 인스턴스를 만들어 사용할 수 있다.


✍ 생성자 함수 사용과 클래스 사용의 차이와 공통점

  • 클래스의 경우, 상속을 지원하는 extends, super 키워드 제공.
  • 생성자의 경우, 상속을 위해
    call(), const 자식.prototype = Object.create(부모.prototype) 을 사용. 참고 게시물
  • 클래스의 경우, 호이스팅이 발생하지 않는 것처럼 동작.
  • 생성자 함수의 경우, 호이스팅 발생.
  • 클래스의 경우, ES6부터 도입되어 IE 지원 불가.

2-1 클래스 상속

class Robot {
     constructor(name) {
       this.name = name;
     }
     sayName() {
       console.log(`이름은 ${this.name} 입니다.`);
     }
   }
   class BabyRobot extends Robot {
     constructor(name) {
       super(name);
       this.ownName = "Joy";
     }
     sayBabyName() {
       this.sayName();
       console.log("Hi");
     }
   }
   const baby = new BabyRobot("ayden");

extends 키워드로 부모 클래스를 상속 받아 부모 클래스의 함수와 property를 사용할 수 있다. 상속을 사용하는 이유는 기본적으로 부모 클래스에서 할 수 있는 것들은 부모에서 하고 부모에 없는 기능을 자식 클래스에 새로 만들어 부모 기능과 자식 기능을 모두 사용하는 것이다.


❓ 자식 클래스에서 부모 기능을 사용하려면 어떻게 할까?

class Parent {
     constructor(one, two, three) {
       this.one = one;
       this.two = two;
       this.three = three;
     }
  class Child extends Parent {
     constructor(one, two, three, four) {
       super(one, two, three);
       this.four = four;
     }

super 키워드를 이용하여 부모 기능을 자식도 사용할 수 있다.
자식 클래스에서 부모 클래스에 있는 one, two, three 를 모두 사용하고, four를 추가적으로 사용하고 싶을 때 super() 키워드를 사용한다.
super() 키워드는 부모 클래스 생성자를 호출하는 것으로 생각하면 된다. 즉, this.one = 자식에게 전달 받은 one 이렇게 되는 것이다. 여기서 this는 자식이 호출했기 때문에 자식 인스턴스를 가르킨다.


✍ super 키워드 사용법.
super()는 부모 class의 property를 불러오고,
super. 는 부모의 메서드를 불러온다.


❓ super 키워드를 사용하지 않는다면?
자식 클래스 생성자 함수에 부모 클래서 생성자 함수 코드를 다 가져와야 한다. 이렇게 되면 그냥 부모 클래스를 사용하는 것과 차이가 없다.
출처

2-2 비공개(private) property

🕵️‍♀️ 비공개 프로퍼티란?
객체 안의 중요한 정보를 안전하게 보호하여 외부로부터 프로그램이 뜻하지 않게 변경되는 것을 막는 역할을 한다.

class UserInfo {
    #password
    constructor(name, pw) {
        this.#password = pw;
    }
}

# 키워드를 사용하여 property를 비공개로 전환할 수 있다.
이때, 비공개 property에 접근하는 방법이 두 가지 있다.

    getPassword() {
        return this.#password
    }
    setPassword(pw) {
        this.#password = pw;
    }

getter, setter 메서드라고 하며, 해당 메서드를 작성하여 클래스 메서드에서 접근할 수 있다. 명칭을 겟터, 셋터 메서드라고 하며 따로 있는 메서드가 아닌, 개발자가 작성하는 메서드이다.

get password(){
	return this.#password;
}
set password(pw){
	this.#password = pw;
}
// user.password() 이 아닌,
user.password                 // get
user.password = 123456;       // set

get, set 키워드를 사용하여 접근할 수도 있다. 함수 앞에 작성되며, 주의할 점은 함수처럼 동작하지 않고 property 처럼 동작한다.
get, set 키워드는 property 처럼 동작하기 때문에 비공개 property에 사용하는 것은 좋지 않다. 데이터를 비공개 했는데, 공개한 것 처럼 보인다.

profile
기록하는 개발자 Ayden 입니다.

0개의 댓글