Class #기본구조 및 new, prototype, ES6

달다로·2024년 6월 4일

JS

목록 보기
11/26
post-thumbnail

📌 Class

  • 뭔가를 만들기 위한 설계 도면이다, 도면으로 비슷한 종류의 여러 객체를 만들 수 있음
  • 클래스 안에는 객체가 가질 수 있는 특징과 행동을 정의한 것들이 존재함
  • 객체 지향 프로그래밍
// class 의 새로운 상자 생성
class Toy {
    constructor(name) {
        this.name = name;
    }
    play() {
        console.log(this.name + "와 함께 놀기!");
    }
}
// 지정
const toy1 = new Toy("Teddy Bear");
const toy2 = new Toy("Toy Car");
// 출력
toy1.play(); // "Teddy Bear와 함께 놀기!" 출력
toy2.play(); // "Toy Car와 함께 놀기!" 출력

🔥 기본적인 객체데이터의 구조

  • firstname 과 lastname 은 속성(property)
  • getFullName(속성) 에 함수(function) 가 할당되어있으면 더이상 속성이 아니라 매소드
  • 속성 과 매소드 를 통틀어서 멤버(member) 라고 칭한다.
const daldaro = {
	firstName: 'Daldaro',
  	lastName: 'Kim',
  	getFullName: function () {
    	return '${this.firstName} ${this.lastName}' // this 부분을 daldaro 라고 해도 무방하다.
    }
}
console.log(daldaro)

📌 새로운 객채를 만드는 매커니즘

1) new

new 로 시작하는 함수는 반드시 대문자로 시작하는 이름을 가져야함

  • new 를 호출을 하면 { } 비어있는 객체가 생성됨
    • 생성자함수 : new woman(달다로, 95) 의 woman 부분! 새로운 객체 데이터를 생성하는 행위
    • 리터럴 : const daldaro = {비어있음} 의 {} 부분! 복잡한 과정을 거치지않고 손쉽게 새로운 데이터를 생성하는 개념
    • 인스턴스 : const daldaro 의 daldaro 부분!
  • 빈 객채를 this 가 참조하도록 변경됨
  • 함수가 종료되면 자동으로 this 를 return 함 (따로 return 을 명시하지 않아도 됨)

🔥 주의사항

  • 다음으로 넘어갈때 ,(컴마) 를 사용하지 않음
  • new 가 거의 필수적으로 사용된디.

예시 1번

function Toy(name) {
    this.name = name;
}

const teddyBear = new Toy("Teddy Bear");

예시 2번

function person(name, age) {
	this.name = name;
  	this.age = age;
  
  	this.getName = () => {
    	return this.name;
    }
}

class Woman {
	constructor(name, age) { // class 와 constructor(생성자) 는 필수로 묶여있어야함
    	this.name = name;
      	this.age = age;
    }
}

getName () {
	return this.name;
}

getAge = () => {
	return this.age;
}
// p = person 함수의 instance
const p = new Person('달다로', 95); // person 과 woman 은 생성자함수 라고 부름 (하나의 객체데이터를 생성함)
const p1 = new Woman('달다로', 95);

console.log(p);
console.log(p.getName());

2) prototype

  • 어떤 것이 처음으로 만들어진 원형이나 기본 틀을 의미한다.
  • 이 틀을 가지고서 다른 함수들이 참조를 해서 사용할 수 있다.
    (과자 틀로 같은모양의 쿠키를 여러번 찍어낼 수 있는 원리)
function User(first, last) {
	this.firstName = first
  	this.lastName = last
}
User.prototype.getFullName = function () { // user가 포함된 모든 것들은 그 안의 함수를 사용할 수 있음
	return `${this.firstName} ${this.lastName}`
}

const daldaro = new User('Daro', 'Dal')
console.log(daldaro.getFullName())

3) ES6 Classes

  • 위의 프로토타입은 원시적으로 사용하는 방식이고 ES6 방식을 사용해서 보다 간결하게 나타낼 수 있다.
    (위의 프로토타입과 값이 같은 점 참고)
  • class 는 constuctor 함수가 필수적이며 constructor function() {} 에서 function 은 생략 가능하다.
Class User {
	constructor(first, last) {
    	this.firstName = first
      	this.lastName = last
    }
  	getFullName() {
    	return `${this.firstName} ${this.lastName}`
    }
}

const daldaro = new User('Daro', 'Dal')
console.log(daldaro.getFullName())

📌내장 클래스 (중첩 클래스)

  • 정의

    • 큰 함수 속에 작은 함수들이 있다.
    • 큰 함수 안에서 작은 함수를 만들고 사용할 수 있다.
    • 작은 함수들은 큰 함수 안에서만 사용 가능하다.
  • function (함수랑 클래스 둘다 가능)

  • object.create (최상위부모, 모든 오브젝트들은 기본적으로 prototype 을 가지고 있다.)

JS

// 큰상자 class ToyBox {...}
class ToyBox {           
    constructor() {
        this.toys = [];
    }

    addToy(toy) {
        this.toys.push(toy);
    }

    listToys() {
        return this.toys;
    }

    // 작은 장난감 상자 class ToyBox {... class Toy {...}}
    class Toy {
        constructor(name) {
            this.name = name;
        }

        getName() {
            return this.name;
        }
    }
}
const myToyBox = new ToyBox();
const teddyBear = new ToyBox.Toy("Teddy Bear");
const toyCar = new ToyBox.Toy("Toy Car");

myToyBox.addToy(teddyBear);
myToyBox.addToy(toyCar);

console.log(myToyBox.listToys().map(toy => toy.getName()));
// ['Teddy Bear', 'Toy Car'] 출력

📌 전역 객체

마치 집 전체를 나타내는 큰 상자이다.
우리가 사용하는 다양한 기능이 있다.

  • document
    • HTML 자체
  • window
    • 브라우저 자체(UI) - 우리가 사용하는 모든 것들
    • 전역 스코프
  • global
    • node.js 환경에서는 글로벌이라고 불림
profile
나이들어서 공부함

0개의 댓글