ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 클래스와 인스턴스
    프론트 공부 2023. 3. 15. 14:00

    클래스

    • 관련 데이터를 모아두는 틀 같은 역할을 한다.
    • 한번만 선언한다.
    • 클래스 안에는 데이터가 없다.
    • 메모리에 올라가지 않는다.

    생성자

    class Person {
      // constructor(생성자)
      constructor(name, age) { // 인자를 받아 할당한다.
        this.name = name; // this는 객체를 지칭한다. 여기서는 Person
        this.age = age; // this.name, this.age는 클래스의 필드(프로퍼티)이다.
      }
    
      // methods(메서드)
      study() {
        console.log(`${this.name}는 공부를 하고 있습니다.`) 
      }
    }

    인스텐스

    • new  키워드를 통해 새로운 인스텐스를 생성할 수 있다.
      class person {
        constructor(name,age,gender){
          this.name = name;
          this.age = age;
          this.gender = gender;
        }
        study(){
          console.log(`${this.name}: hello!`);
        }
    let name1 =new person('민수','20','males');
    let name2 =new person('영희','24','female')
    let name3 =new person('철수','30','males')

    메서드

    • 객체 안에 메서드를 생성할 수 있다.
      class Person {
        // constructor(생성자)
        constructor() { 
          this.age = 0;
      }
    	sum(x,y){
        	return x + y
        }
      }
      
      let a = new Person();
      a.sum(1,2)//3

    getter/setter

    getter

    • 객체의 특정 프로퍼티 값을 가져오도록 하기 위함 메소드
    • this.age 를 호출하면 get age() {} 가 무한 루프에 빠질 수 있어 this._age 형태로 사용한다

    setter

    • 객체의 특정 프로퍼티 값을 설정하기 위한 메소드
    • this.age = value 를 호출하면 set age() {} 가 무한 루프에 빠질 수 있어 this._age = value 형태로 사용한다
     getter/ setter
     class Person {
        // constructor(생성자)
        constructor() { 
          this.age = 0;
      }
      get age(){
        return this._age;
        }
      set age(newage){
        this.age = newage;
        console.log(this.age);
        }
      }
    
      let humam = new Person();
      humam.age = 26;
      humam.age;
    • getter 는 Person.age()를 사용하여 프로퍼티 값을 읽으려 할때 실행.
    • setter 는 Person.age = newage 로 값을 할당할 때 사용한다.

     

    '프론트 공부' 카테고리의 다른 글

    비동기  (0) 2023.03.21
    프로토 타입 언어  (0) 2023.03.15
    객체 지향 프로그래밍  (0) 2023.03.15
    모던 자바스크립트 Deep Dive 12~14장 공부  (0) 2023.03.14
    html을 활용하여 자기소개 페이지 만들기  (0) 2023.02.14
Designed by Tistory.