Backend/JS & TS

자바스크립트 - part 2

퐁고 2023. 3. 23. 17:07
반응형

객체 지향 ES6 클래스


  • 객체를 만들기 위한 템플릿 (붕어빵 툴 == 생성자 함수, 붕어방 == 객체)
  • 프로토타입 기반 생성자 함수를 사용할 수 있지만 에전 방식, 요즘에는 class를 사용한다
  • 클래스에서 객체를 만들 수 있고, 클래스를 통해 객체를 만든 것을 인스턴스라 부른다

용어

  • 생성자 constructor: new 키워드로 객체(인스턴스)를 생성할 때 호출되는 함수
  • 생성자 프로퍼티 위에 필드 프로퍼티
  • 인스턴스의 메소드
class Fruits{
		// 필드
		const name;
		const emoji;
		// 생성자 함수
    constructor(name,emoji){
        this.name = name;
        this.emoji = emoji;
    }
		// 메서드
    display(){
        console.log(`${this.name}: ${this.emoji}`);
    }
}

const banana = new Fruits('banana','🍌');

console.log(banana);
banana.display();

클래스에서만 사용할 경우

  • 클래스 내부의 프로퍼티, 메소드 부분에서 static 사용
  • 클래스 레벨의 메서드에서는 this 참조 불가
  • 생성자 위에 클래스 레벨의 프로퍼티 지정가능
  • 생성된 인스턴스로 접근 불가 클래스 레벨로만 접근 가능
  • 예시 Math()
class Fruits{
    static Max = 10;
    constructor(name,emoji){
        this.name = name;
        this.emoji = emoji;
    }
    static random(){
        return new Fruits('apple','🍎');
    }

    display(){
        console.log(`${this.name}: ${this.emoji}`);
    }
}

const apple = Fruits.random();
console.log(apple);
console.log(Fruits.Max);

접근 제어자 - 캡슐화

  • 내부에서 사용한 코드를 외부에서 접근 불가능하게 해줌
  • private(#), public(기본), protected(_)
    • private - 클래스 내부에서만 접근 가능, #사용
    • protected - 클래스 내부와 자식 클래스에서만 접근을 허용, _언더바 사용

getter, setter

  • 접근자 프로퍼티 ()
  • get을 사용해주면 접근할 때 메서드처럼 ()로 호출안하고 속성에 접근하듯이 접근가능
  • set을 사용해주면 할당을 할 때 호출
  • 행동을 나타내는 게 아닌데 메소드로 사용해주었을 때 조금 더 제어을 해주려면 get,set 사용
class Student{
    constructor(firstName, lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }
    get fullName(){
        return `${this.lastName} ${this.firstName}`
    }
    set fullName(value){
        console.log(value);
    }
}
const name = new Student('경영','김');
console.log(name.fullName); 
name.fullName = '김경영';

상속

  • 부모 클래스의 생성자, 필드, 메서드가 자식 클래스와 겹칠 때 일일히 적기보다는 상속을 해준다.
class Dog extends Animal{
    constructor(name,color,newName){
        super(name,color);
        this.newName = newName;
    }
    play(){
        console.log(`${this.newName}${this.name} 같이 놀기`);
    }
    // 부모 클래스의 메서드를 상속받은 자식 클래스가 같은 이름의 메서드를 새로 정의해 주는 것을 오버라이딩
    act(){
        console.log(`${this.name}가 뛰어논다.`);
    }
}
const dog = new Dog('강아지','하얀','주인');
dog.act();
dog.play();

오버로딩(Overloading) : 같은 이름의 메서드 여러 개를 정의하고, 매개변수의 유형과 개수가 다르게해서 다양한 유형의 호출 응답
오버라이딩(Overriding) : 상위 클래스가 가지고 있는 메서드를 하위 클래스가 재정의해서 사용

Web APIs


Web APIs

  1. DOM API
  2. setTimeout
  3. setInterval
  4. fetch
  5. event listener
  6. Ajax

JSONPlaceholder

Fetch()


  • 프로미스를 리턴
  • 프로미스는 리스폰스라는 오브젝트를 리턴
  • 네트워크 통신 기법
  • 외부 api를 가져오기(호출) json
fetch(api)
.then((res) => res.json())
.then((data) => console.log(data))

DOM


예제

**<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script defer src="index1.js"></script>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <div class="header">
        <h1>javascript</h1>
    </div>
    <div class="content">
        <form id="todo-form">
            <div>
                <label for="todo-input"></label>
                <input type="text" id="todo-input">
                <button class="submit">저장</button>
            </div>
        </form>
        <ul id="todo-list">
            <!-- <li class="item">1.할 일</li>
            <li class="item">2.할 일</li>
            <li class="item">3.할 일</li>
            <li class="item">4.할 일</li> -->
        </ul>
    </div>
</body>
</html>**
*{
    margin: 0;
    padding: 0;
}

.header{
    background-color: #3b5999;
    color: #fff;
    padding: 1rem;
    text-align: center;
}

.content{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;
    padding: 1rem;
}

button{
    border: none;
    background: #3b5999;
    color: #fff;
    padding: 0.3rem;
    border-radius: 0.2rem;
}

#todo-form{
    margin-top: 3rem;
    list-style: none;
    width: 300px;
    margin-top: 8rem;
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 1rem;
}

label{
    font-weight: bold;
    margin-right: 0.5rem;

}

input{
    padding: 0.1rem;
    height: 20px;
}

#todo-list{
    margin-top: 3rem;
    list-style: none;
    width: 300px;
    padding-left: 2rem;

}

.item{
    padding: 1rem;
}

기본 사용법

// id 선택
// const form = document.getElementById('todo-form');
const form = document.querySelector('#todo-form');
console.log(form);-> 확인하기

// class 선택
const list = document.querySelectorAll('.item');
console.log(list);
  • 삭제하기
const todos = document.querySelector('#todo-list');
todos.remove();
  • 배경 넣기
const todos = document.querySelector('#todo-list');
todos.style.background = 'green';
  • 글자 바꾸기
todos.firstElementChild.textContent = 'hello'
todos.lastElementChild.textContent = 'hi'
  • html 삽입
**todos.lastElementChild.innerHTML = '<h1>안녕하세요</h1>**
  • 버튼 이벤트
const btn = document.querySelector('.submit');

//btn.addEventListener(어떤 이벤트, 어떤 기능);
btn.addEventListener('click', () => {
    alert('클릭!');
})
  • 버튼 이벤트 클릭 시 새로고침이 기본 (이것을 안하게 하기)
btn.addEventListener('click', (e) => {
		e.preventDefault();
		console.log(e) // 이벤트 할 수 있는거 확인
		// e.target.style.color = 'red'; 클릭하면 글자 빨강으로 바꾸기    
		alert('클릭!');
});
  • 함수 형태로 빼주기
btn.addEventListener('click', onSubmit);

function onSubmit(e){
		e.preventDefault();
		console.log(e)
}
  • 버튼 이벤트 클릭 후 input에 글자 가져오기
const input = document.querySelector('#todo-input');

btn.addEventListener('click', onSubmit);

function onSubmit(e){
		e.preventDefault();
		const li = document.createElement('li');
		li.appendChild(document.createTextNode(input.value));
		todos.appendChild(li);
}

WEB3-Ajax-1.수업소개